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


Check if a function exists in a class before calling 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')时,没有任何问题。但是当我调用一个不存在的函数时,它不起作用。现在我想先检查类test中的函数是否存在,然后再调用函数call_user_func

是否有一个函数可以检查

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

您正在寻找初学者的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调用,这表明您没有使用自动加载器
更重要的是:您所做的只是检查file_exists,而不是该类是否已加载。然后,如果您的代码段每次都以相同的值执行两次$this->controller,您的代码将生成致命错误。
至少通过将您的require更改为require_once来开始解决此问题......

您可以使用

PHP函数method_exists()

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

或者还有:

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

从 PHP 5.3 开始,您还可以使用:

if(method_exists($this, $model))
    return forward_static_call([$this, $model], $extra, $parameter);

使用 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';
}