0

For functions I can just assign the function name to a string variable, but how do I do it for class methods?

$func = array($this, 'to' . ucfirst($this->format));
$func(); // fails in PHP 5.3

This seems to work:

$this->{"to{$this->format}"}();

But it's way too long for me. I need to call this function many times...

4

3 回答 3

1

That's not really a function? Why don't use standard method for functions?

function func() {
$func = array($this, 'to' . ucfirst($this->format));
return $func;
}

then output it with

func();
于 2013-03-30T20:37:21.167 回答
1

You can use call_user_func:

class A
{

  function thisIsAwesome()
  {
    return 'Hello';
  }

}

$a = new A;

$awesome = 'IsAwesome';

echo call_user_func(array($a, 'this' . $awesome));

Although it's still quite long. You could write your own function to do it:

function call_method($a, $b)
{
  return $a->$b();
}

$a = new A;

$awesome = 'IsAwesome';

echo call_method($a, 'this' . $awesome);

Which is a litter shorter.

于 2013-03-30T21:00:43.467 回答
1

One option is to use php's call_user_func_array();

Example:

call_user_func_array(array($this, 'to' . ucfirst($this->format)), array());

You can also use the self keyword or the class name with the scope resolution operator.

Example:

$name = 'to' . ucfirst($this->format);
self::$name();

className::$name();

However, what you have posted using php's variable functions is also completely valid:

$this->{"to{$this->format}"}();

call_user_func_array() is probably considered more readable than using variable functions, but from what I've read (like here), variable functions tend to out perform call_user_func_array().

What did you mean by the variable function being too long?

于 2013-03-30T21:06:37.547 回答