전창한
전창한

Reputation: 21

in php why does isn't work

class GrandClass {
    public $data;
    public function __construct() {
        $this->someMethodInTheParentClass();
    }
    public function someMethodInTheParentClass() {
        $this->$data = 123456;
    }
}

class MyParent extends GrandClass{
    public function __construct() {
        parent::__construct();
    }
}

class Child extends MyParent {
    // public $data;
    public function __construct() {
        parent::__construct();
    }
    public function getData() {
        return $this->data; 
    }
}

$a = new Child();
var_dump($a->getData());

PHP Notice: Undefined variable: data in D:\test.php on line 7

PHP Fatal error: Cannot access empty property in D:\test.php on line 7

Upvotes: 0

Views: 68

Answers (3)

Vuer
Vuer

Reputation: 149

Constructors in MyParent and Child classes are unnecessary.

Upvotes: 0

Kamlesh Gupta
Kamlesh Gupta

Reputation: 505

Use  `$this->data = 123456; `instead of`  $this->$data = 123456;` in below function

public function someMethodInTheParentClass() {
        $this->data = 123456;
}

Upvotes: 2

AmmyTech
AmmyTech

Reputation: 738

update your function someMethodInTheParentClass with below using $this->data = 123456;

 public function someMethodInTheParentClass() {
        $this->data = 123456;
    }

Upvotes: 4

Related Questions