Andrew
Andrew

Reputation: 2851

In PHP, how do we get parent class variables?

I was under the impression that child class inherit the properties of their parent. The following, however, is output null in class B... Can someone tell me how I access properties from the parent class?

$aClass = new A();
$aClass->init();

class A {

    function init() 
    {
        $this->something = 'thing';
        echo $this->something; // thing
        $bClass = new B();
        $bClass->init();
    }

}

class B extends A {

    function init() 
    {
        echo $this->something; // null - why isn't it "thing"?
    }
}

Upvotes: 2

Views: 5390

Answers (3)

hek2mgl
hek2mgl

Reputation: 157967

There are several errors in your code. I've corrected them. The following script should work as expected. I hope the code comments are helpful:

class A {

    // even if it is not required you should declare class members
    protected $something;

    function init() 
    {
        $this->something = 'thing';
        echo 'A::init(): ' . $this->something; // thing
    }

}

// B extends A, not A extends B
class B extends A {

    function init() 
    {
        // call parent method to initialize $something
        // otherwise init() would just being overwritten
        parent::init();
        echo 'B::init() ' . $this->something; // "thing"
    }
}


// use class after(!) definition
$aClass = new B(); // initialize an instance of B (not A)
$aClass->init();

Upvotes: 4

Sam
Sam

Reputation: 1902

We access parent class members in PHP using the following syntax:

parent::$variableName

Or

parent::methodName(arg, list)

Upvotes: 0

Ayush
Ayush

Reputation: 42450

Your second class defined should be class B extends A, and not class A extends B.

Upvotes: 1

Related Questions