Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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

}

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?

like image 200
S.Visser Avatar asked Oct 23 '13 09:10

S.Visser


3 Answers

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

like image 186
Elias Van Ootegem Avatar answered Nov 04 '22 08:11

Elias Van Ootegem


You can use the PHP function method_exists():

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

or also:

if (method_exists($class_instance, 'method_name'))
call_user_func(etc...);
like image 15
ProGM Avatar answered Nov 04 '22 10:11

ProGM


From PHP 5.3, you can also use:

if(method_exists($this, $model))
    return forward_static_call([$this, $model], $extra, $parameter);
like image 4
GiuServ Avatar answered Nov 04 '22 09:11

GiuServ