0

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?

2 Answers 2

4

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);

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer. I'm very well aware about that, but sometimes you just fail to see a typo, even after checking 10 times...
Just because sleep doesn't... ^^
2

You are using variable variable instead of accessing the variable directly

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

With

 $this->attr = $attr;

2 Comments

Wooow! I was very disapointed, but now I feel like an idiot! Thanks a lot!
Leave the system , Play some games GOW is nice .. Take a nap then continue programming ... This fix most similar programming errors

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.