jam8
jam8

Reputation: 1

what mean string in {}?

I have string

$name = 'user';

$run->{$name};

And i have result notice :

Undefined property: run::$user

I have in controller method user, but in error i see string ang $ char.

Is this is a some special char ?

Upvotes: 0

Views: 79

Answers (5)

Amber
Amber

Reputation: 526613

obj->{$foo} is equivalent to obj->bar if the string in $foo is 'bar'.

See http://php.net/manual/en/language.variables.variable.php for more details.

If obj->bar is actually a method, you should be calling it as obj->bar()...

And thus object->{$foo}() - note the parentheses.

Upvotes: 3

Maxim Krizhanovsky
Maxim Krizhanovsky

Reputation: 26699

Refer to variable variables The braces are required when only part of the string is the variable name and PHP would interpret it incorrectly. In all other cases they are optional and are placed for better readability (the same way as () braces are used in expressions). Since you are referring to method, and not a property, you have to use (). It's the same even when you don't use variable variables:

$foo->user // access to property
$foo->user() // method call

Upvotes: 0

Alex
Alex

Reputation: 9471

If you have a method in the controller (an instance of which you've captured in $run) you can use:

$run->$name();

Upvotes: 0

Daniel Gruszczyk
Daniel Gruszczyk

Reputation: 5622

$name = "user";
$run->{$name}();

to run a method user();

Upvotes: 0

Senad Meškin
Senad Meškin

Reputation: 13756

$run->{$name} is like you have written $run->user , this is used when you want to access property of object using value of variable

so if $name = 'user';

then $run->{$name} will try to get property with the name 'user'

Upvotes: 0

Related Questions