简体   繁体   English

如何在父类中设置对象并在子类中使用它?

[英]How can I set an object in a parent class and use it in child classes?

Here's some working code: 这是一些工作代码:

class A {
    public $Foo;

    public function GetFoo() {
        $this->Foo = 'Bar';
    }
}

class B extends A {
    function __construct() {
        $this->GetFoo();
        echo $this->Foo;
    }
}

$b = new B(); // Outputs "Bar"

Is there any way I can make this "prettier" (ie without the A::GetFoo() method)? 有什么办法可以使我变得“更漂亮”(即没有A :: GetFoo()方法)? I would've thought that wrapping the population of the $this->Foo inside a A::__construct() would work, but it doesn't. 我本来以为将$ this-> Foo的总体包装在A :: __ construct()中会起作用,但是没有用。

Just to wrap it up, here's what I want: class A instantiates my DB object and that object is usable for every child class of A. 总结一下,这就是我想要的:类A实例化我的DB对象,并且该对象可用于A的每个子类。

Perhaps you're overriding the parent's constructor without calling in from B ? 也许您没有从B调用就覆盖了父级的构造函数?

class A {

    protected $Foo = null;

    public function __construct() {
        $this->Foo = 'Bar';
    }

}

class B extends A {

    public function __construct() {
        parent::__construct();
        echo $this->Foo;
    }

}

From the PHP manual : PHP手册

"Class properties must be defined as public, private, or protected. If declared using var without an explicit visibility keyword, the property will be defined as public ." “类属性必须定义为public,private或protected。如果使用var声明而没有显式的可见性关键字,则该属性将定义为public 。”

So, your class B can see $this->Foo . 因此,您的B类可以看到$this->Foo You don't have to call GetFoo() first. 您不必先调用GetFoo() You must, however, call the parent constructor first if you need to reference $this->Foo inside of your constructor for class B . 但是,如果需要在类B的构造函数中引用$this->Foo ,则必须首先调用父构造函数。

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

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