Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:
<?php
//文件包含
//? 文件包含的本质:将外部文件内容复制到当前文档中
//? 文件包含中的变量共享当前作用域
//include 动态,用到时再加载
//require 静态,应写到顶部;加载失败,中断退出
include __DIR__ . '/out/demo1.php';
echo $email . '<br>';
require __DIR__ . '/out/demo2.php';
echo $name . '<br>';
//include 加载失败,继续执行不中断
include __DIR__ . '/out/demo3.php';
echo $name . '<br>';
//require 加载失败,中断退出
require __DIR__ . '/out/demo3.php';
echo $name . '<br>';
<?php
//常规成员
class Person
{
//私有变量,仅限在当前类中使用
private $name;
//可继承, 可在本类或子类中使用, 不对外公开
protected $province;
//公共
public $country = 'China';
public function getName()
{
//$this引用当前类
return $this->name;
}
//魔术方法,系统调用,实例化自动调用
public function __construct($name)
{
$this->name = $name;
}
}
$user1 = new Person('张三');
//echo $user1->name.'<br>';
//echo $user1->province.'<br>';
echo $user1->country . '<br>';
echo $user1->getName() . '<br>';
//静态成员
class Person2
{
//静态属性
private static $name = 'Lily';
//类常量: 与实例无关,用类访问
const COUNTRY = 'USA';
//静态方法
public static function getName()
{
//引用当前类
return self::$name;
}
}
echo Person2::COUNTRY . '<br>';
echo Person2::getName() . '<br>';
<?php
//类的扩展/抽象/最终
//protected,extends,abstract,final,parent
class Person
{
private $name;
protected $province;
protected function getName()
{
return $this->name;
}
protected function __construct($name)
{
$this->name = $name;
}
}
class Student extends Person
{
//属性的扩展
private $lesson;
private $score;
//重写方法
public function __construct($name, $lesson, $score)
{
//parent引用父类
parent::__construct($name);
$this->lesson = $lesson;
$this->score = $score;
}
//扩展方法
public function getInfo()
{
return parent::getName() . " $this->lesson 课程为 $this->score 分";
}
}
$student1 = new Student('张三', 'php', '99');
echo $student1->getInfo() . '<br>';
//抽象类,不想让用户直接使用父类
abstract class Demo1
{
//抽象方法:只有方法名,参数列表,没有具体实现{}
abstract protected function hello($name);
}
// new Demo1;
//最终类,无法被继承/扩展
// final class Demo1
// {
// }
class Demo2 extends Demo1
{
//工作类中必须实现父类中的抽象成员
public function hello($name): string
{
return 'Hello , ' . $name;
}
}
echo get_parent_class(new Demo2) . '<br>';
echo call_user_func([new Demo2, 'hello'], '牛老师');
<?php
//interface,implements
interface A
{
//类常量
const SOURCE = 'PHP';
//必须抽象,必须public
//!不建议声明抽象构造方法
public function m1();
public function m2();
}
interface B
{
}
interface C
{
}
class User implements A, B, C
{
//普通类实现,须实现所有抽象成员
public function m1()
{
}
public function m2()
{
}
}
abstract class User2 implements A, B, C
{
//抽象类实现,允许有不实现的抽象成员
public function m1()
{
}
}
//查看当前类实现的所有接口
print_r(class_implements('User'));