Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Call a instance method with call_user_func within the same class

Tags:

php

I'm trying to use call_user_func to call a method from another method of the same object, e.g.

class MyClass {     public function __construct()     {         $this->foo('bar');     }     public function foo($method)     {         return call_user_func(array($this, $method), 'Hello World');     }      public function bar($message)     {         echo $message;     } } 

new MyClass; Should return 'Hello World'...

Does anyone know the correct way to achieve this?

Many thanks!

like image 755
Fred Avatar asked Nov 26 '10 19:11

Fred


People also ask

What is __ call () in PHP?

When you call a method on an object of the Str class and that method doesn't exist e.g., length() , PHP will invoke the __call() method. The __call() method will raise a BadMethodCallException if the method is not supported. Otherwise, it'll add the string to the argument list before calling the corresponding function.

How do I call a function from one function to another in PHP?

There are two methods for doing this. One is directly calling function by variable name using bracket and parameters and the other is by using call_user_func() Function but in both method variable name is to be used. call_user_func( $var );

What is Call_user_func_array?

Synopsis. mixed call_user_func_array ( function callback , array params ) The call_user_func_array() function is a special way to call an existing PHP function. It takes a function to call as its first parameter, then takes an array of parameters as its second parameter.


2 Answers

The code you posted should work just fine. An alternative would be to use "variable functions" like this:

public function foo($method) {      //safety first - you might not need this if the $method      //parameter is tightly controlled....      if (method_exists($this, $method))      {          return $this->$method('Hello World');      }      else      {          //oh dear - handle this situation in whatever way          //is appropriate          return null;      } } 
like image 187
Paul Dixon Avatar answered Sep 18 '22 02:09

Paul Dixon


This works for me:

<?php class MyClass {     public function __construct()     {         $this->foo('bar');     }     public function foo($method)     {         return call_user_func(array($this, $method), 'Hello World');     }      public function bar($message)     {         echo $message;     } }  $mc = new MyClass(); ?> 

This gets printed out:

wraith:Downloads mwilliamson$ php userfunc_test.php      Hello World 
like image 33
Matt Williamson Avatar answered Sep 20 '22 02:09

Matt Williamson