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...
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?
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();
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.