Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 392
Richard Avatar asked Oct 27 '25 06:10

Richard


1 Answers

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'}();
like image 141
Alex Netkachov Avatar answered Oct 28 '25 21:10

Alex Netkachov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!