Wednesday, 28 January 2009

{}, curly braces, in Php, not mysql

Variable parsing

When a string is specified in double quotes or with heredoc,
variables are parsed within it.

There are two types of syntax: a
simple one and a
complex one.
The simple syntax is the most common and convenient. It provides a way to
embed a variable, an array value, or an object
property in a string with a minimum of effort.

The complex syntax was introduced in PHP 4, and can be recognised by the
curly braces surrounding the expression.

Simple syntax

If a dollar sign ($) is encountered, the parser will
greedily take as many tokens as possible to form a valid variable name.
Enclose the variable name in curly braces to explicitly specify the end of
the name.

"$beer's taste is great"// works; "'" is an invalid character for variable names
echo "He drank some $beers";   // won't work; 's' is a valid character for variable names but the variable is "$beer"
echo "He drank some ${beer}s"// works
echo "He drank some {$beer}s"// works

Similarly, an array index or an object property
can be parsed. With array indices, the closing square bracket
(]) marks the end of the index. The same rules apply to
object properties as to simple variables.

// These examples are specific to using arrays inside of strings.
// When outside of a string, always quote array string keys and do not use
// {braces}.

// Show all errors

$fruits = array('strawberry' => 'red''banana' => 'yellow');

// Works, but note that this works differently outside a string
echo "A banana is $fruits[banana].";

// Works
echo "A banana is {$fruits['banana']}.";

// Works, but PHP looks for a constant named banana first, as described below.
echo "A banana is {$fruits[banana]}.";

// Won't work, use braces.  This results in a parse error.
echo "A banana is $fruits['banana'].";

// Works
echo "A banana is " $fruits['banana'] . ".";

// Works
echo "This square is $square->width meters broad.";

// Won't work. For a solution, see the complex syntax.
echo "This square is $square->width00 centimeters broad.";

For anything more complex, you should use the complex syntax.

No comments:

My photo
London, United Kingdom

Facebook & Twitter