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. 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. 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? I've done a lot of reading in comments on PHP.net and other places and I couldn't find anything concise.
With parent::method()
you call the overridden method (not only the constructor), so your solution is the right one. 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() ?
精彩评论