I'm wondering why the following code won't print out anything. I'm trying to access Bar::$some_var
from method in parent class. Where Bar::$some_var
is defined in it's constructor.
I've tried using self::$some_var
and static::$some_var
in Foo::hello()
but neither worked. Do I have to make $some_var
static
?
class Foo {
private $some_var;
public function __construct() {
$this->some_var = 5;
}
public function hello() {
print $this->some_var;
}
}
class Bar extends Foo {
public function __construct() {
$this->some_var = 10;
}
}
$bar = new Bar();
$bar->hello();
Thanks in advance.
private
makes a member variable unavailable outside of a class. You need to use protected
to allow extending classes to have access to that variable.
protected $some_var;
See Visibility
Your class variable cannot be private if you would like your child class to access it. Try protected instead and it should work!
anyway in your code the problem is visibility of $some_var. It has to be almost protected, public will also work
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.