[英]PHP OOP inheritance issue. Can't access parent variable from child class
I have a class like this: 我有这样的课:
class A {
public $var = "";
function __construct() {
$this->var = "value";
}
}
And a child class like this: 像这样的子班:
class B extends A {
function __construct() {
// Is this correct?
parent::__construct();
}
function my_function() {
// Or this?
// $options is an instantiation of A.
global $options;
echo $this->var;
}
}
The problem I was having is that when I called the my_function() method, the value of var was empty. 我遇到的问题是,当我调用my_function()方法时,var的值为空。 After reading on php.net for a while I found out that when a child class has its own constructor, the parent constructor is overridden which is why my variable was empty. 在php.net上阅读了一段时间后,我发现当子类具有自己的构造函数时,父构造函数被覆盖,这就是为什么我的变量为空的原因。 My question is if the way I'm calling parent::__construct() is the right solution or if I should just globalize the instantiated object that I created in my script? 我的问题是,我调用parent :: __ construct()的方式是否是正确的解决方案,还是只应全球化在脚本中创建的实例化对象? I've done a lot of reading in comments on PHP.net and other places and I couldn't find anything concise. 我已经在PHP.net和其他地方的注释中进行了大量阅读,但找不到简明扼要的内容。
With parent::method()
you call the overridden method (not only the constructor), so your solution is the right one. 使用parent::method()
可以调用重写的方法(不仅是构造函数),因此您的解决方案是正确的。 In your case you can omit the constructor completely and just set the value, when you declare the property. 在您的情况下,您可以完全省略构造函数,而在声明属性时只需设置值即可。
class A {
public $var = "value";
}
Additional: Global variables are ugly in every way. 补充:全局变量在各个方面都很丑陋。 Use them only, if you have really good reasons to do so and never, because its more convenient. 仅当您确实有充分理由这样做时才使用它们,而决不要这样做,因为这样做更方便。
The following "implementation" ... 以下“实现” ...
$instanceOfB = new B();
$instanceOfB->my_function();
results in "value" ... as excpected. 产生“价值”……如所期望的。
What has been your way of calling my_function() ? 您调用my_function()的方式是什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.