Fred
Fred

Reputation: 1031

PHP Call a instance method with call_user_func within the same class

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!

Upvotes: 37

Views: 49877

Answers (3)

Gordon
Gordon

Reputation: 316939

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

A constructor does not return anything.

Upvotes: 3

Paul Dixon
Paul Dixon

Reputation: 300825

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;
     }
}

Upvotes: 42

Matt Williamson
Matt Williamson

Reputation: 40193

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

Upvotes: 23

Related Questions