2015-10-08 58 views
0

我試圖減少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')); 
?> 

這甚至可能嗎?

回答

0

你在你的構造函數的名稱有一個錯字和第二,調用method_exists()功能,你應該通過$this作爲第一個參數,而不是$this->obj時:

public function __construct($action,$postArray) 
    { 

     $this->data = $postArray; 
     if (method_exists($this, $action)) { 
      $this->{$action}(); 

     }else{ 
      die('Method does not exist'); 
     } 
    } 
相關問題