Check if a function exists in a class before calling call_user_func()

后端 未结 4 776
青春惊慌失措
青春惊慌失措 2020-12-14 16:35

In the following code I call a class with call_user_func().

if(file_exists(\'controller/\' . $this->controller . \'.controller.php\')) {
             


        
4条回答
  •  攒了一身酷
    2020-12-14 17:06

    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)
        );
    }
    

    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...

提交回复
热议问题