找回密码
 注册
搜索
热搜: java php web
查看: 743|回复: 1

PHP变量解析

[复制链接]
发表于 2009-1-27 16:03:28 | 显示全部楼层 |阅读模式
  有两种语法,一种简单的和一种复杂的。简单语法最通用和方便,它提供了解析变量,数组值,或者对象属性的方法。
简单语法

  如果遇到美元符号($),解析器会尽可能多地取得后面的字符以组成一个合法的变量名。如果你想明示指定名字的结束,用花括号把变量名括起来。

<?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}}";
?>
发表于 2009-1-27 17:30:55 | 显示全部楼层
怎么发到这儿了?
不过还是顶一下
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|手机版|小黑屋|软晨网(RuanChen.com)

GMT+8, 2024-9-20 16:44

Powered by Discuz! X3.5

Copyright © 2001-2023 Tencent Cloud.

快速回复 返回顶部 返回列表