- 论坛徽章:
- 1
|
变量解析
当用双引号或者定界符指定字符串时,其中的变量会被解析。
有两种语法,一种简单的和一种复杂的。简单语法最通用和方便,它提供了解析变量,数组值,或者对象属性的方法。
复杂语法是 PHP 4 引进的,可以用花括号括起一个表达式。
简单语法
如果遇到美元符号($),解析器会尽可能多地取得后面的字符以组成一个合法的变量名。如果你想明示指定名字的结束,用花括号把变量名括起来。
- <?php
- $beer = 'Heineken';
- echo "$beer's taste is great"; // works, "'" is an invalid character for varnames
- echo "He drank some $beers"; // won't work, 's' is a valid character for varnames
- echo "He drank some ${beer}s"; // works
- echo "He drank some {$beer}s"; // works
- ?>
复制代码
同样也可以解析数组索引或者对象属性。对于数组索引,右方括号(])标志着索引的结束。对象属性则和简单变量适用同样的规则,尽管对于对象属性没有像变量那样的小技巧。
- <?php
- // These examples are specific to using arrays inside of strings.
- // When outside of a string, always quote your array string keys
- // and do not use {braces} when outside of strings either.
- // Let's show all errors
- error_reporting(E_ALL);
- $fruits = array('strawberry' => 'red', 'banana' => 'yellow');
- // Works but note that this works differently outside string-quotes
- 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.";
- ?>
复制代码
对于任何更复杂的情况,应该使用复杂语法。
复杂(花括号)语法
不是因为语法复杂而称其为复杂,而是因为用此方法可以包含复杂的表达式。
事实上,用此语法你可以在字符串中包含任何在名字空间的值。仅仅用和在字符串之外同样的方法写一个表达式,然后用 { 和 } 把它包含进来。因为不能转义“{”,此语法仅在 $ 紧跟在 { 后面时被识别(用“{\$”或者“\{$”来得到一个字面上的“{$”)。用一些例子可以更清晰:
- <?php
- // Let's show all errors
- error_reporting(E_ALL);
- $great = 'fantastic';
- // 不行,输出为:This is { fantastic}
- echo "This is { $great}";
- // 可以,输出为:This is fantastic
- echo "This is {$great}";
- echo "This is ${great}";
- // Works
- echo "This square is {$square->width}00 centimeters broad.";
- // Works
- echo "This works: {$arr[4][3]}";
- // This is wrong for the same reason as $foo[bar] is wrong
- // outside a string. In otherwords, it will still work but
- // because PHP first looks for a constant named foo, it will
- // throw an error of level E_NOTICE (undefined constant).
- echo "This is wrong: {$arr[foo][3]}";
- // Works. When using multi-dimensional arrays, always use
- // braces around arrays when inside of strings
- echo "This works: {$arr['foo'][3]}";
- // Works.
- echo "This works: " . $arr['foo'][3];
- echo "You can even write {$obj->values[3]->name}";
- echo "This is the value of the var named $name: {${$name}}";
- ?>
复制代码 |
|