Search code examples
phpoopfatal-error

PHP call_user_func alternative


I am looking for a pretty equivalent in PHP to its function call_user_func. The problem I am encountering with this function is that it does not go into an "object mode". By this, I mean I cannot use $this and other stuff in the class, so pretty much in two words: not oop.

I need this basically as I am dealing with the requested url, parsing it, and seeing if everything is ok and so on, and then doing the following lines:

call_user_func(array(ucfirst( $controller . "Controller" ),  '_initAction'), $param);       
call_user_func(array(ucfirst( $controller . "Controller" ), $action . 'Action'), $param);

as I want to dynamically call the "Controller" and its actions. But I cannot use $this in the $action methods as it is not OOP.

Here the message I get:

Fatal error: Using $this when not in object context in E:\htdocs\wit\application\controller\InformationController.php on line 6

So I hope that somebody could help me.

Could you also tell me if I am approaching this problem in a wrong way?

PS: Please don't recommend me any MVC frameworks that take care of this stuff. I like Zend, but sometimes, its just too heavy :(( I need a lightweight setup for this.


Solution

  • You can call the object method by passing object in first element of the callback:

    $class = ucfirst($controller . "Controller");
    $controller = new $class();
    call_user_func(array($controller,  $action . 'Action'), $param);
    

    Actually, you can even use

    $controller = new $class();
    $controller->{$action . 'Action'}();