PHP 5中如何动态调用子类方法?
<?php
class foo
{
//this class is always etended, and has some other methods that do utility work
//and are never overrided
public function init()
{
//what do to here to call bar->doSomething or baz->doSomething
//depending on what class is actually instantiated?
}
function doSomething()
{
//intentionaly no functionality here
}
}
class bar extends foo
{
function doSomething()
{
echo "bar";
}
}
class baz extends foo
{
function doSomething()
{
echo "baz";
}
}
?>
<?php
class foo
{
//this class is always etended, and has some other methods that do utility work
//and are never overrided
public function init()
{
//what do to here to call bar->doSomething or baz->doSomething
//depending on what class is actually instantiated?
}
function doSomething()
{
//intentionaly no functionality here
}
}
class bar extends foo
{
function doSomething()
{
echo "bar";
}
}
class baz extends foo
{
function doSomething()
{
echo "baz";
}
}
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你只需要调用 $this->doSomething(); 在你的 init() 方法中。
由于多态性,将在运行时根据子对象的类调用子对象的正确方法。
You just have to call $this->doSomething(); in your init() method.
Due to polymorphism, the correct method of the child object will be called at runtime depending on the class of the child.