Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Can';无法访问父类属性_Php_Inheritance_Visibility - Fatal编程技术网

Php Can';无法访问父类属性

Php Can';无法访问父类属性,php,inheritance,visibility,Php,Inheritance,Visibility,当我使用父类属性时,它返回NULL,我不知道为什么会发生这种情况,示例代码: class Foo { public $example_property; public function __construct(){ $this->example_property = $this->get_data(); } public function get_data() { return 22; // this is pro

当我使用父类属性时,它返回
NULL
,我不知道为什么会发生这种情况,示例代码:

class Foo
{

    public $example_property;

    public function __construct(){
        $this->example_property = $this->get_data();
    }

    public function get_data() {
        return 22; // this is processed dynamically.
    }
}

class Bar extends Foo
{
    public function __construct(){}

    public function Some_method() {
        return $this->example_property; // Outputs NULL
    }
}

实际上,当我使用
constructor
设置属性值时会发生这种情况,但是如果我静态地设置值(例如:
public$example\u property=22
,它将不再返回
NULL
,这是因为应该显式调用父构造函数:

class Bar extends Foo
{
    public function __construct() {
        parent::__construct();
    }


    public function Some_method() {
        return $this->example_property; // Outputs NULL
    }
}
但仔细看看——如果你没有声明
Bar
构造函数,应该执行父构造函数。也许你没有向我们展示完整的代码

因此,如果您在子类中有
\uu构造
,并且希望使用父构造函数-您应该显式地调用它,正如我所说的
父::\uu构造();


如果子类中没有
\uu construct
方法,则将调用父类的方法。

幸运的是,不需要它。扩展类继承构造函数。从您的示例中,它应该立即起作用。我不知道为什么会发生这种情况,但在添加
父类::\uu construct()之后
成功了!o.o严格按照您的代码示例,
$bar=new bar();echo$bar->Some_method()
outputs
22
@u\u mulder更改了我的投票,请您编辑。这对我有效。您能用您用来获取该属性的代码编辑帖子吗?我使用了@u\u mulder答案,它起了作用!所以您必须有一个
\u构造()
在您的
Bar
类中,因为它是继承的。是的,实际上我有,这是原因吗?是的。如果没有显式调用,
父::\u construct()
将被重写