Friday 12 April 2019

php - Unable to view property inherited from parent class

As you said, the $Balance property is private. Private means it is not accessible from outside the defining class, not even from child classes that inherit the property.


class Foo {
private $bar="baz";
public function __construct(){echo $this->bar;}
public function getBar(){return $this->bar;}
}
class Bar extends Foo {
public function __construct(){echo $this->bar;}
}
new Foo;
new Bar;

If we run this code we get the error:


baz
PHP Notice: Undefined property: Bar::$bar in php shell code on line 2

So, you have two choices. You can use your getter instead:


class Foo {
private $bar="baz";
public function __construct(){echo $this->bar;}
public function getBar(){return $this->bar;}
}
class Bar extends Foo {
public function __construct(){echo $this->getBar();}
}
new Foo;
new Bar;

Or, you can declare the property as protected instead of private:


class Foo {
protected $bar="baz";
public function __construct(){echo $this->bar;}
public function getBar(){return $this->bar;}
}
class Bar extends Foo {
public function __construct(){echo $this->bar;}
}
new Foo;
new Bar;

Either of these give the expected output:


baz
baz

See documentation here for more details on property and method visibility.

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...