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!
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.
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 );
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.
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; } }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With