[英]How to dynamically call child class methods in 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";
}
}
?>
You just have to call $this->doSomething(); 您只需要调用$ this-> doSomething();。 in your init() method.
在您的init()方法中。
Due to polymorphism, the correct method of the child object will be called at runtime depending on the class of the child. 由于多态性,子对象的正确方法将在运行时根据子类进行调用。
public function init() {
$this->doSomething();
}
$obj = new bar();
$obj->doSomething(); // prints "bar"
$obj2 = new baz();
$obj->doSomething(); // prints "baz"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.