How can a parent class's method access an subclass's overridden variable?
If I have a subclass that is overriding a protected variable, and the parent class has the function to do stuff with that variable, how do I get that function to use the value it is overridden with?
class Superclass {
protected $map;
public function echoMap()
{
开发者_如何学编程 foreach ($this->map as $key=>value)
{
echo "$key:$value";
}
}
}
and
class Subclass extends Superclass {
protected $map = array('a'=>1, 'b'=>2);
}
and when I run the following
$subclass = new Subclass();
$subclass->echoMap();
I would expect it to return
a:1
b:2
but $this->map
is empty in the parent class. What should I do instead to get the behavior I want?
Edit: There was a bug in the constructors, not in the example posted above. It works as expected.
PHP does work the way you describe. The only thing I can see is in your example, Subclass does not extend Superclass. I assume this is a mistake in your example only. Check to make sure all classes actually do extend the correct class, and check to make sure you have no typos in variable names.
See http://codepad.viper-7.com/kDrbIh for an example of it working.
Even though it looks to be just a typo (not extending the super class), you should try initializing your variables in the constructor of both classes.
function __construct() {
// initialize protected values
}
精彩评论