简体   繁体   English

PHP从父构造函数中构造的子类中获取父类变量

[英]PHP Get parent class variables from child class constructed in the parent constructor

With the following code snippet, why does $this->foo return NULL in the B child class constructor? 使用以下代码段,为什么$this->foo在B子类构造函数中返回NULL From what I've read I was under the impression that a child class inherits all its parent variables and methods 根据我的阅读,我给人的印象是子类继承了其所有父变量和方法

$a = new A();

class A {
    protected $foo;

    public function __construct() {
        $this->foo = "Hello World";

        $b = new B();
    }
}

class B extends A {
    public function __construct() {
        var_dump($this->foo);
    }
}

The selected answer of this question seems to suggest $this->foo should be accessible. 问题的选定答案似乎表明$this->foo应该可以访问。

Is it because B is being constructed from within its parent class? 是因为B是从其父类中构造的吗? If that is the case, how can I access the variable in the child class? 在这种情况下,如何访问子类中的变量?

You're doing new A() and then separately you're doing new B() . 您正在执行new A() ,然后分别在执行new B() You have two entirely independent object instances. 您有两个完全独立的对象实例。 It doesn't matter that one instantiation happens in the constructor of A , that's entirely irrelevant. A的构造函数中发生一个实例无关紧要,这是完全不相关的。 It also doesn't matter that B extends A . B扩展A也不重要。 You have two independent objects, and object instances do not share data implicitly, which is what you seem to be expecting. 您有两个独立的对象,并且对象实例不会隐式共享数据,这正是您所期望的。

Since B 's constructor overrides its parent's constructor, it's not executing any of A 's code either, so essentially nothing is happening when you instantiate a new B . 由于B的构造函数会覆盖其父级的构造函数,因此它也不执行A的任何代码,因此,当实例化一个新的B时,实际上什么也没有发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM