mimipc
mimipc

Reputation: 1374

PHP object inheritance : how to access parent attributes?

I wrote this little test script for PHP object inheritance :

<?php

class A {
    protected $attr;

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

    public function getAttr() {
        return $this->attr;
    }
}

class B extends A {

}

$b = new B(5);
echo $b->getAttr();

This displays nothing! Why doesn't it display 5? Isn't class B supposed to be like class A?

Upvotes: 0

Views: 75

Answers (2)

bwoebi
bwoebi

Reputation: 23787

The error is here:

$this->$attr = $attr;

you assign here to $this->{5} (the value of $attr).

Write, to address the property:

$this->attr = $attr;
//     ^------ please note the removed `$` sign

To notice what is going on in such cases, try to dump your object: var_dump($b);

Upvotes: 4

Baba
Baba

Reputation: 95161

You are using variable variable instead of accessing the variable directly

 $this->$attr = $attr;
        ^
        |----- Remove This

With

 $this->attr = $attr;

Upvotes: 2

Related Questions