当用双引号或者定界符指定字符串时,其中的变量会被解析。
有两种语法,一种简单的和一种复杂的。简单语法最通用和方便,它提供了解析变量,数组值,或者对象属性的方法。
复杂语法是 PHP 4 引进的,可以用花括号括起一个表达式。
简单语法
如果遇到美元符号($),解析器会尽可能多地取得后面的字符以组成一个合法的变量名。如果你想明示指定名字的结束,用花括号把变量名括起来。
<?php |
同样也可以解析数组索引或者对象属性。对于数组索引,右方括号(])标志着索引的结束。对象属性则和简单变量适用同样的规则,尽管对于对象属性没有像变量那样的小技巧。
<?php |
对于任何更复杂的情况,应该使用复杂语法。
复杂(花括号)语法
不是因为语法复杂而称其为复杂,而是因为用此方法可以包含复杂的表达式。
事实上,用此语法你可以在字符串中包含任何在名字空间的值。仅仅用和在字符串之外同样的方法写一个表达式,然后用 { 和 } 把它包含进来。因为不能转义“{”,此语法仅在 $ 紧跟在 { 后面时被识别(用“{/$”或者“/{$”来得到一个字面上的“{$”)。用一些例子可以更清晰:
<?php |