Correction status:Uncorrected
Teacher's comments:
<?php //对象三大特征:继承封装,多态 //继承是代码复用的手段,关键字extends //父类 class Demo { public $name; protected $age; private $sex; const SITE_NAME = 'PHP中文网'; public function __construct($name,$age) { $this->name = $name; $this->age = $age; } // public function __get($name) // { // if(isset($this->$name)){ // return $this->$name; // } // return '非法属性'; // } } //子类 class Demo_1 extends Demo { private $salary; //子类中的常量可以重写 const SITE_NAME = 'PHP.cn'; //子类的构造方法必须将父类的构造方法重新声明一遍 //将父类的方法重写-多态 public function __construct($name, $age,$salary) { $this->salary = $salary; //访问父类关键字parent parent::__construct($name, $age); } public function __get($name) { if(isset($this->$name)){ return $this->$name; } return '非法属性'; } } $demo_1 = new Demo_1('Peter', 28,8000); echo $demo_1->name.'<br>'; echo $demo_1->age.'<br>'; //私有属性,只能在父类和子类中使用,外部不可使用 echo $demo_1->show.'<br>'; //属性不存在时自动调用__get()方法 echo $demo_1->salary.'<br>'; echo Demo::SITE_NAME.'<br>'; echo Demo_1::SITE_NAME.'<br>';
点击 "运行实例" 按钮查看在线实例