[英]Trying to understand PHP OOP
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. 我正在尝试从父类中的方法访问
Bar::$some_var
。 Where Bar::$some_var
is defined in it's constructor. 其中
Bar::$some_var
在其构造函数中定义。
I've tried using self::$some_var
and static::$some_var
in Foo::hello()
but neither worked. 我试过在
Foo::hello()
使用self::$some_var
和static::$some_var
,但都没有用。 Do I have to make $some_var
static
? 我必须使
$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. private
使成员变量在类外部不可用。 You need to use protected
to allow extending classes to have access to that variable. 您需要使用
protected
来允许扩展类访问该变量。
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. 无论如何,在您的代码中,问题是$ some_var的可见性。 It has to be almost protected, public will also work
它必须受到几乎保护,公众也将工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.