在调用call_user_func()之前检查类中是否存在函数 [英] Check if a function exists in a class before calling call_user_func()

查看:235
本文介绍了在调用call_user_func()之前检查类中是否存在函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我使用call_user_func()调用一个类.

In the following code I call a class with 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';
}

假设控制器具有以下代码.

Let’s say that the controller has the following code.

class test {

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

}

当我打电话给call_user_func('test', 'test_function')时,没有任何问题.但是,当我调用一个不存在的函数时,它将无法正常工作.现在,我想先检查类test中的函数是否存在,然后再调用函数call_user_func.

When I call call_user_func('test', 'test_function') there isn't any problem. But when I call a function that does not exist, it does not work. Now I want to check first if the function in the class test does exist, before I call the function call_user_func.

是否有一个函数可以检查某个类中是否存在某个函数,或者是否可以通过其他方法进行检查?

Is there a function that checks if a function exists in an class or is there another way I can check this?

推荐答案

您在寻找 is_callable 函数完成的:

You're looking for method_exists for starters. But what you should check, too is whether or not the method is callable. This is done by the helpfully named is_callable function:

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

但这仅仅是开始.您的代码段包含显式的require调用,这表明您未在使用 require_once 开始解决此问题.

But that's just the start of things. Your snippet contains explicit require calls, which suggests you're not using an autoloader.
What's more: all you're doing is check file_exists, not if the class was already loaded. Your code, then, will generate a fatal error if, per chance your snippet gets executed twice with the same values for $this->controller.
Begin fixing this by, in the very least, changing your require to require_once...

这篇关于在调用call_user_func()之前检查类中是否存在函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆