我試圖減少API類上的代碼,我期望做的是在調用類內部的方法之前確保存在方法。在運行之前動態檢查可用的方法
將傳遞方法作爲變量需要查看該方法是否存在於類內部然後運行該方法。
示例代碼如下:
<?php
class Test {
private $data;
private $obj;
public function __contruct($action,$postArray)
{
$this->data = $postArray;
if (method_exists($this->obj, $action)) {
//call method here
//This is where it fails
$this->$action;
}else{
die('Method does not exist');
}
}
public function methodExists(){
echo '<pre>';
print_r($this->data);
echo '</pre>';
}
}
//should run the method in the class
$test = new Test('methodExists',array('item'=>1,'blah'=>'agadgagadg'));
//should die()
$test2 = new Test('methodNotExists',array('item'=>1,'blah'=>'agadgagadg'));
?>
這甚至可能嗎?