简体   繁体   中英

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?

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

You are using variable variable instead of accessing the variable directly

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

With

 $this->attr = $attr;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM