Karina
Karina

Reputation: 998

How to assign an object function to a variable?

class example()
{
    function shout($var)
    {
        echo 'shout'.$var;
    }

    function whisper($var, $bool)
    {
        if($bool)
        {
           echo $var;
        }
    }
}

$obj = new example();

if($var) 
{
    $func = $obj->shout();
}else
{
    $func = $obj->whisper();
}

I want to prepare the function variable first for later use instead of putting conditions in a loop. Is there a possible way to do it?

Upvotes: 6

Views: 5057

Answers (2)

davidtbernal
davidtbernal

Reputation: 13684

You can put the function name in a string:

if($var) 
{
    $func = 'shout';
}else
{
    $func = 'whisper';
}

Later on:

$obj->$func

You can also use a callback:

if($var)
{
    $func = array($obj, 'shout');
}else
{
    $func = array($obj, 'whisper');
}

Later:

call_user_func($func);

or:

call_user_func_array($func, $args);

Upvotes: 4

user149341
user149341

Reputation:

You can call methods by name:

if ($var) {
    $fn = 'shout';
} else {
    $fn = 'whisper';
}

$obj->$fn();

Upvotes: 7

Related Questions