2013-10-23 23 views
15

在下面的代碼中,我調用了一個類call_user_func()在調用call_user_func()之前檢查函數中是否存在函數

if(file_exists('controller/' . $this->controller . '.controller.php')) { 
    require('controller/' . $this->controller . '.controller.php'); 
    call_user_func(array($this->controller, $this->view)); 
} else { 
    echo 'error: controller not exists <br/>'. 'controller/' . $this->controller . '.controller.php'; 
} 

可以說控制器具有以下代碼。

class test { 

    static function test_function() { 
     echo 'test'; 
    } 

} 

當我打電話call_user_func('test', 'test_function')沒有問題。但是,當我調用一個不存在的函數時,它不起作用。現在我想首先檢查te類測試中的函數是否存在,然後再調用函數call_user_func

是否有一個函數,檢查是否在一個類中存在一個函數或有其他方式,我可以檢查這個?

+7

[method_exists()](http://php.net /manual/en/function.method-exists.php) –

+0

謝謝@MarkBaker! –

+2

不是每個現有的方法都可以調用 - > [is_callable](http://php.net/manual/en/function.is-callable.php) – a4c8b

回答

39

您正在尋找初學者的method_exists。但是你要檢查的是應該是也可能是可調用。這是通過有趣的is_callable函數完成的:

if (method_exists($this->controller, $this->view) 
    && is_callable(array($this->controller, $this->view))) 
{ 
    call_user_func(
     array($this->controller, $this->view) 
    ); 
} 

但是,這只是事情的開始。您的摘錄包含明確的require來電,這表明您沒有使用autoloader
更重要的是:你所做的只是檢查file_exists,如果該類已經加載,則不行。那麼,如果你的代碼片段被執行了兩次,並且其值爲$this->controller,那麼你的代碼將會產生一個致命錯誤。
開始解決這個由,在最起碼,改變你的requirerequire_once ...

+0

關於'is_callable'的TIL,謝謝! –

+0

如果你正在調用'is_callable()',你需要調用'method_exists()'嗎? – MrWhite

+2

@ w3d:'is_callable'理論上可以返回'true',即使你沒有調用方法(關閉分配給屬性)。做這兩項檢查可能是一種偏執狂,但這是最安全的方式。此外,最後我檢查了'method_exists'表現更好,所以如果返回false,'is_callable'將不會被調用(微優化,我知道,但仍然...)。但這並不是說你沒有意見,但我認爲這兩種功能都值得在這方面提及...... –

9

您可以使用PHP函數method_exists()

if (method_exists('ClassName','method_name')) 
call_user_func(etc...); 

,或者也:

if (method_exists($class_instance,'method_name')) 
call_user_func(etc...); 
+0

偉大它使你的理解變得非常簡單。 –

0

使用method_exists($this->controller, $this->view)。舉例來說:

if(file_exists('controller/' . $this->controller . '.controller.php') && 
    method_exists($this->controller,$this->view)) { 

    require('controller/' . $this->controller . '.controller.php'); 
    call_user_func(array($this->controller, $this->view)); 

} else { 
    echo 'error: controller or function not exists <br/>'. 'controller/' . $this->controller . '.controller.php'; 
} 
+1

儘管您需要調用'method_exists()'_after_包含類文件。 – MrWhite

3

從PHP 5.3,你也可以使用

if(method_exists($this, $model)) 
    return forward_static_call([$this, $model],$extra, $parameter); 
相關問題