PHP对象继承:如何访问父属性


PHP object inheritance : how to access parent attributes?

我为PHP对象继承编写了这个小测试脚本:

<?php
class A {
    protected $attr;
    public function __construct($attr) {
        $this->$attr = $attr;
    }
    public function getAttr() {
        return $this->attr;
    }
}
class B extends A {
}
$b = new B(5);
echo $b->getAttr();

这没有显示任何内容!为什么不显示5 ?B级不应该和A级一样吗?

错误在这里:

$this->$attr = $attr;

你在这里赋值给$this->{5} ($attr的值)。

写属性地址:

$this->attr = $attr;
//     ^------ please note the removed `$` sign

要注意在这种情况下发生了什么,请尝试转储对象:var_dump($b);

您正在使用变量variable而不是直接访问变量

 $this->$attr = $attr;
        ^
        |----- Remove This

 $this->attr = $attr;