PHP-子类重写父类属性问题

问题还原

新建父类文件

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 属性时,将这个属性的访问权限由 publicprotected 。尝试修改子类:

1
2
3
4
5
6
7
8
9
<?php
class Dog
{
// protected $hasLeg = true;
public $hasLeg = true;
public function __consruct()
{
}
}

再次执行脚本

1
2
$ php Dog.php

总结

PHP 子类在重在父类属性时,重载的属性的访问权限要大于等于父类属性的访问权限(private < protected < public),否则会报错!


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!