2

I was wondering if there is such a thing like dynamic Class and Function calling possible?

For example, I have these two operations:

$this->foo->value();

$this->bar->value();

and I would like to call it somewhat like this:

$this->($var)->value();

right now I'm doing it this way (but would love the above methode)

if($var == 'foo')
    $this->foo->value(); 
else 
    $this->bar->value();
1
  • PHP is interpreted so you can use objects without defining them first. Commented Oct 16, 2013 at 17:49

1 Answer 1

1

You almost had it.

$var = 'foo';
$this->$var->value();

Is equivalent to

$this->foo->value():

Similarly:

$var = 'bar';
$this->foo->$var();

Is equivalent to;

$this->foo->bar();
Sign up to request clarification or add additional context in comments.

3 Comments

What's your position on curly braces? $this->{$var}->value(); ? I tend to like them because they make it a bit more visually clear that the method is a variable.
Cool thanks, that actually work.. do you also know if something like this is possible: $this->($this->pageClass->value)->value(); ?
wow thanks cale_b.. that did the trick :D I would upvote you two but sadly I can`t yet as new member ;)

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.