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...

2
  • Could you please clarify what member function you are trying to call and how you would call it without using a variable? It's hard to tell what is the function name and/or if there are any parameters based on your question. Commented Mar 30, 2013 at 20:35
  • I'm trying to access a non-static class method, eg. $this->toHtml() Commented Mar 30, 2013 at 20:39

3 Answers 3

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?

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

Any variable string can be called as a function. Take a look at php variable functions documentation.
Sorry, but according to the examples, calling a variable string as a function should be done this way: function func() { bblabla } $variable = 'func'; $variable() => so $variable() calls func()
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.