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

S.V*_*ser 25 php

在下面的代码中,我调用了一个类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';
}
Run Code Online (Sandbox Code Playgroud)

让我们说控制器有以下代码.

class test {

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

}
Run Code Online (Sandbox Code Playgroud)

当我打电话call_user_func('test', 'test_function')没有问题.但是,当我调用一个不存在的函数时,它不起作用.现在我想在调用函数之前首先检查te类测试中的函数是否存在call_user_func.

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

Eli*_*gem 49

你正在寻找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)
    );
}
Run Code Online (Sandbox Code Playgroud)

但那只是事情的开始.您的代码段包含显式require调用,表明您没有使用自动加载器.
更重要的是:你正在做的就是检查file_exists,而不是班级是否已经加载.那么,如果您的代码段被执行两次并且具有相同的值,则您的代码将生成致命错误$this->controller.
开始修复这个,至少,改变你requirerequire_once...

  • @ w3d:`is_callable`可以理论上返回`true`,即使你没有调用方法(分配给属性的闭包).做这两项检查可能有点偏执,但这是最安全的方式.此外,最后我检查过,`method_exists`执行得更好,所以如果返回false,`is_callable`将不会被调用(微优化,我知道,但仍然......).但这并不是说你没有意义,但我认为这两个功能在这方面都值得一提...... (2认同)

Pro*_*oGM 10

你可以使用php函数method_exists():

if (method_exists('ClassName','method_name'))
call_user_func(etc...);
Run Code Online (Sandbox Code Playgroud)

或者:

if (method_exists($class_instance,'method_name'))
call_user_func(etc...);
Run Code Online (Sandbox Code Playgroud)