即使這是一個老問題,這是一個使用ReflectionMethod我的解決方案:
class whale
{
function __construct()
{
// some code here
}
function myfunc()
{
//Get the class name
$name = get_called_class();
//Create a ReflectionMethod using the class and method name
$reflection = new \ReflectionMethod($class, 'test');
//Call the method
$reflection->invoke($this);
}
}
使用ReflectionMethod類的好處是,你可以傳遞參數數組和檢查哪一個是需要在你打電話的方法:
//Pass a list of arguments as an associative array
function myfunc($arguments){
//Get the class name
$name = get_called_class();
//Create a ReflectionMethod using the class and method name
$reflection = new \ReflectionMethod($class, 'test');
//Get a list of parameters
$parameters = $reflection->getParameters()
//Prepare argument list
$list = array();
foreach($parameters as $param){
//Get the argument name
$name = $param->getName();
if(!array_key_exists($name, $arguments) && !$param->isOptional())
throw new \BadMethodCallException(sprintf('Missing parameter %s in method %s::%s!', $name, $class, $method));
//Set parameter
$list[$name] = $arguments[$name];
}
//Call the method
$reflection->invokeArgs($this, $list);
}
我知道我已經把錯誤的類名稱,但這只是一個例子,而不是我會在任何地方實現它的東西。 – Sarfraz 2009-12-22 08:31:43
從邏輯上來看,'魚'應該是父類,'鯨'是孩子;} – Strae 2009-12-22 11:50:51
@DaNieL鯨魚不是魚。 – 2011-08-24 10:40:32