John Doe
John Doe

Reputation: 298

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" (i.e. without the A::GetFoo() method)? I would've thought that wrapping the population of the $this->Foo inside a A::__construct() would work, but it doesn't.

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.

Upvotes: 0

Views: 110

Answers (2)

AJ.
AJ.

Reputation: 28174

From the PHP manual:

"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."

So, your class B can see $this->Foo. You don't have to call GetFoo() first. You must, however, call the parent constructor first if you need to reference $this->Foo inside of your constructor for class B.

Upvotes: 1

deceze
deceze

Reputation: 522032

Perhaps you're overriding the parent's constructor without calling in from B?

class A {

    protected $Foo = null;

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

}

class B extends A {

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

}

Upvotes: 2

Related Questions