Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP curly brace syntax for member variable

First question on SO and it's a real RTM candidate. But I promise you I've looked and can't seem to find it. I'll happily do a #headpalm when it turns out to be a simple thing that I missed.

Trying to figure out Zend Framework and came across the following syntax:

$this->_session->{'user_id'} 

I have never seen the curly braces syntax used to access what appears to be a member variable. How is it different than

$this->_session->user_id 

I'm assuming that the _session is irrelevant, but including it in the question since it may not be.

Are the curly braces just a cleanliness convention that attempts to wrap the compound variable name user_id? Or is it some kind of a special accessor?

Any pointers into TFM so I can R up would be humbly appreciated.

Many thanks. Please be gentle.

like image 771
David Weinraub Avatar asked Jul 18 '09 16:07

David Weinraub


People also ask

What is curly braces PHP?

Introduction. PHP allows both square brackets and curly braces to be used interchangeably for accessing array elements and string offsets. For example: $array = [1, 2]; echo $array[1]; // prints 2 echo $array{1}; // also prints 2 $string = "foo"; echo $string[0]; // prints "f" echo $string{0}; // also prints "f"

What is the meaning of {} in Java?

In Java when you open a curly brace it means that you open a new scope (usually it's a nested scope).

How do you put curly braces in HTML?

“}” U+007D Right Curly Bracket Unicode Character.

What are curly braces in coding?

Different programming languages have various ways to delineate the start and end points of a programming structure, such as a loop, method or conditional statement. For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.


2 Answers

Curly braces are used to explicitly specify the end of a variable name. For example:

echo "This square is {$square->width}00 centimeters broad.";  

So, your case is really a combination of two special cases. You're allowed to access class variables using curly braces and like so:

$class->{'variable_name'} // Same as $class->variable_name $class->{'variable' . '_name'} // Dynamic values are also allowed 

And in your case, you're just surrounding them with the curly brace syntax.

See the PHP manual, "complex (curly) syntax."

like image 146
James Skidmore Avatar answered Oct 11 '22 13:10

James Skidmore


I know the syntax just when using variable variables:

$userProp = 'id'; $this->_session->{'user_'.$userProp}; 
like image 35
Gumbo Avatar answered Oct 11 '22 12:10

Gumbo