在调用 call_user_func() 之前检查类中是否存在函数

php
2022-08-30 13:35:35

在下面的代码中,我调用了一个带有 .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')testcall_user_func

是否有函数可以检查类中是否存在函数,或者是否有其他方法可以检查它?


答案 1

您正在为初学者寻找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_once...requirefile_exists$this->controllerrequire


答案 2

您可以使用 PHP 函数method_exists()

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

或者:

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

推荐