问题还原
新建父类文件
1 2 3 4 5 6 7 8
| <?php class Animal { public $hasLeg = false; public function __consruct() { } }
|
新建子类文件
1 2 3 4 5
| <?php class Dog extend Animal { protected $hasLeg = true; }
|
执行脚本
1 2 3 4
| $ php Dog.php PHP Fatal error: Access level to Dog::$hasLeg must be public (as in class Animal) in /www/code/html/test/Dog.php on line 4
Fatal error: Access level to Dog::$hasLeg must be public (as in class Animal) in /www/code/html/test/Dog.php on line 4
|
经过比较父类、子类发现,子类在重在父类的 $hasLeg
属性时,将这个属性的访问权限由 public
→protected
。尝试修改子类:
1 2 3 4 5 6 7 8 9
| <?php class Dog { public $hasLeg = true; public function __consruct() { } }
|
再次执行脚本
总结
PHP 子类在重在父类属性时,重载的属性的访问权限要大于等于父类属性的访问权限(private
< protected
< public
),否则会报错!