今天再看PHP手册时候发现一个问题,那就是PHP子类对象不能直接访问父类的属性,这实在让人疑惑,现在先记录,以后看有什么解释没有。例子:
class MyClass
{
public $public = 'Public';
protected $protected = 'Protected';
private $private = 'Private';
function printHello()
{
echo "This is Myclass".PHP_EOL;
echo $this->public.PHP_EOL;
echo $this->protected,PHP_EOL;
echo $this->private,PHP_EOL;
}
}
class MyClass2 extends MyClass
{
public $public = 'Publi2c';
protected $protected = 'Protected2';
function printHello2()
{
echo $this->public.PHP_EOL;
echo $this->protected,PHP_EOL;
echo parent::$public,PHP_EOL; //此时,会报错,Uncaught Error: Access to undeclared static property: MyClass::$public
}
}
$obj2 = new MyClass2();
$obj2->printHello2();