父类的方法如何访问子类的重写变量?
如果我有一个重写受保护变量的子类,并且父类具有对该变量执行操作的函数,那么如何让该函数使用它被重写的值?
class Superclass {
protected $map;
public function echoMap()
{
foreach ($this->map as $key=>value)
{
echo "$key:$value";
}
}
}
我
class Subclass extends Superclass {
protected $map = array('a'=>1, 'b'=>2);
}
当我运行以下命令时,
$subclass = new Subclass();
$subclass->echoMap();
希望它返回,
a:1
b:2
但是 $this->map
在父类中为空。我应该怎么做才能获得我想要的行为?
编辑: 构造函数中有一个错误,而不是上面发布的示例中的错误。它按预期工作。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
PHP 确实按照您描述的方式工作。我唯一能看到的是在你的例子中,子类不扩展超类。我认为这只是您的示例中的错误。检查以确保所有类实际上都扩展了正确的类,并检查以确保变量名称中没有拼写错误。
请参阅 http://codepad.viper-7.com/kDrbIh 了解其工作示例。
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.
尽管它看起来只是一个拼写错误(没有扩展超类),但您应该尝试在两个类的构造函数中初始化变量。
函数 __construct() {
// 初始化受保护的值
}
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
}