S.Visser S.Visser - 7 months ago 59
PHP Question

check if function exists in class before calling call_user_func()

In the following code I call a class with


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';

Lets say that the controller has the following code.

class test {

static function test_function() {
echo 'test';


When I call
call_user_func('test', 'test_function')
there is no problem. But when i call a function that does not exists it does not work. Now I want to check first if the function in te class test does exists, before I call the function

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


You're looking for method_exists for starters. But what you should check, too is wether 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)))
        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...