eskimo
eskimo

Reputation: 2624

Can I use a variable value in $this in php

I was wondering if I can use a variable when using $this to call a function. It looks different than this question as it doesn't require to use the class as a variable. Also the suggested answer here was not provided there.

Say sometimes $x == 1 and sometimes $x == 2. Could you do:

if($x == 1)
 $var = 'name_1';

if($x == 2)
 $var = 'name_2';

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

Instead of:

if($x = 1)
 $this->name_1->a_function_here();

if($x = 2)
 $this->name_2->a_function_here();

Upvotes: 1

Views: 50

Answers (1)

Valdeir Psr
Valdeir Psr

Reputation: 702

Yes you can.

Just use it $this->{$var}->your_function();

Edit: "PhD thesis" for those who want to understand more.

A "complete" answer to other users who may have the same question.

Sometimes it is better to use variables with function names to make the system more dynamic. You can do this with the mattresses.

Curly braces may also be used, to clearly delimit the property name. They are most useful when accessing values within a property that contains an array, when the property name is made of mulitple parts, or when the property name contains characters that are not otherwise valid

http://php.net/manual/pt_BR/language.variables.variable.php

Upvotes: 1

Related Questions