批改状态:合格
老师批语:很认真
<?php//类的声明与实例化//1.类的声明class Demo1{//类成员:类属性,类常量,类方法public $name = '王佳祥';//类的实例构造方法/器public function __construct(){}}//2.类的实例化:就是创建对象的过程//类中的构造方法必须用:new 来调用$demo = new Demo1();var_dump($demo);//实例与对象,在不引起误会的场景下,可以通用echo '<hr>';//动态类,将类名称放到一个变量中$className = 'Demo1';$obj = new $className;echo get_class($obj);

<?php//类中成员:类属性,类方法class Demo2{//类的属性//公共成员:在类的内部和外部都可以访问,都可见public $name = '闷油瓶';public $options = ['七星鲁王','怒海潜沙','云顶天宫'];//heredoc,nowdoc都支持public $table = <<<HEREDOC<table border="1" cellspacing="0" cellpadding="10px"><tr><td>id</td><td>name</td><td>age</td></tr><tr><td>1001</td><td>张起灵</td><td>100</td></tr><tr><td>1002</td><td>吴邪</td><td>30</td></tr></table>HEREDOC;//静态属性:如果这个属性仅使用一次,可以不创建类实例,而直接通过类来调用public static $color = '红色';//抽象属性,没有被初始化的属性,默认为nullpublic $sex;}//类的实例化$demo2 = new Demo2;//类中的成员属性的访问echo $demo2->name;echo $demo2->table;//访问静态成员使用双冒号:范围解析符echo Demo2::$color;var_dump($demo2->sex);

<?php//类中的方法class Demo3{//类属性 public :访问限定符,用来声明类成员的作用域public $name = '吴邪';public $age = 30;public static $color = 'red';//类方法public function write1(){//访问类属性$user = new Demo3;//访问类成员return "姓名:{$user->name},年龄:{$user->age}";}public function write2(){//声明一个变量,声明在方法中的变量,不是属性,是私有变量/局部变量$sex = '男';//访问类属性 self:类引用//$user = new self; $this 会自动创建,$this是只读的,不能被更新//访问类成员 $this:类实例引用return "姓名:{$this->name},年龄:{$this->age}";}//类方法中访问类外部成员:变量函数public function write3(){//调用外部函数$str = hello();//外部变量return $str . $GLOBALS['username'];}//实际项目中,外部成员应该通过方法参数注入到方法,而不是在方法中直接调用public function write4(Closure $hello,string $username){return $hello() . $username;}//静态方法:不依赖类实例,可以用类直接调用public static function write5(){//静态成员属于类,不属于类实例,所以不能使用类实例的引用$thisreturn "颜色:" . self::$color;}}//客户端代码$user = new Demo3;echo $user->write1().'<br>';echo $user->write2().'<br>';//外部函数function hello(){return 'hello';}$hello = function(){return 'Hello';};$username = '张起灵';echo $user->write3().'<br>';echo $user->write4($hello,$username).'<br>';echo $user->write5().'<br>';

<?php//类成员的访问控制class Demo4{//public:公共成员,默认值,新版本不能省略public $name = '王胖子';//private:私有成员,只能在本类中使用private $age = 40;//protected:受保护的,只可以在子类和本类中使用,外部不能用protected $job = '卖古玩';public function write(){return "姓名:{$this->name},年龄:{$this->age},工作:{$this->job}";}}//子类class Demo4_1 extends Demo4{public function write(){return "姓名:{$this->name},年龄:{$this->age},工作:{$this->job}";}}//类外部$user = new Demo4;echo $user -> name;echo '<hr>';echo $user->write();echo '<hr>';//调用子类访问echo (new Demo4_1)->write();

<?php//类的继承/扩展//变量就是数据复用,函数是代码复用,继承就是类的复用//final:类前加禁止类扩展class Demo5{//属性protected $name = '黑瞎子';//方法// final:方法禁止重写public function write(){return "姓名:{$this->name}";}}//扩展类class Rob extends Demo5{//1.扩展//属性扩展protected $age = 40;//方法扩展public function write(){return parent::write() . ",年龄:{$this->age}";//return "姓名:{$this->name},年龄:{$this->age}";}}$rob = new Rob;echo $rob->write();

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号