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 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
new MyClass; Should return 'Hello World'...
A constructor does not return anything.
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;
}
}