zanderwar
zanderwar

Reputation: 3730

Can't access property from parent class

The only thing I'm trying to achieve is to be able to access the Sql property in class A from class B, but my understanding must be completely off the grid.

I tried:

class A {
    public $Sql; /*object*/

    public function __construct() {
        $this->Sql = new MySQLi("localhost", "user", "password", "database");
    }
}

class B extends A {

    public function __construct() {
        $this->foo();
    }

    public function foo() {
        var_dump($this->Sql); // NULL
        var_dump(parent::Sql); // Error due to Sql not being a constant, can't set an object as a constant.
    }

}

$A = new A();
$B = new B();

But the code is not behaving as I would hope it does.

Hoping someone can point me in the right direction on where I'm going wrong.

Upvotes: 2

Views: 33

Answers (1)

Rizier123
Rizier123

Reputation: 59701

$A = new A();
$B = new B();

These two lines above create 2 different object, which don't have anything to do with each other.

So since you also have a constructor in class B the parent constructor doesn't get called implicit, means you have to change your code and call the constructor from class A in class B, e.g.

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

Upvotes: 4

Related Questions