对于双引号中的变量问题,
1. ${variable_name} 和{$variable_name},可以把variable_name理解为在脚本中的变量名除了“$”的其它部分,该怎么写就直接写(object除外)。
例如
<?php
$array = array('name' => 'jack');
echo "Hello! ${array['name']}";//works
echo "Hello! ${array["name"]}";//works, even use the double quote
echo "Hello! {$array['name']}";//works
?>
即使是variable variable也可以
<?php
$var_name = 'str';
$str = 'jack';
echo "Hello! ${$var_name}";// in the php script is $$var_name
?>
所以,对于使用了"{}"类型的string parse,只要把variabel_name部分当作脚本中的变量名除"$"以外的部分处理即可(object除外)。值得注意的是,无论是"${}"还是"{$}","$"与"{"之间不能有任何字符,必须紧跟。
=============================================================================
2.php解释器对于string parsing是使用了贪婪的方式,也就是说,出现了"$"以后,php会尽可能多地匹配变量名。
例如
<?php
$string = 'China';
$str = 'America';
echo "$string";//output the China.
?>
例子中不会输出$str的值,因为php会尽可能多地去匹配,因此$string会被匹配出
当然这个例子有点不妥当,因为怎么也不可能输出$str的值,只是为了说明php是贪婪的方式。
=============================================================================
3.在"${}"和"{$}"模式中,对于数组变量中,key是字符串且不用单引号或双引号的情况,php会首先去找常量进行匹配,没有才去数组中匹配,可以参考第一点所说的。
例如
<?php
define('name_1', 'name_2');
$array = array(
'name_1' => 'Alva',
'name_2' => 'Jack'
);
echo "${array[name_1]}";//output Jack
echo "${array['name_1']}";//output Alva
?>
在其它情况下,key不用单引号或者双引号,是会直接匹配数组中的值
例如
<?php
define('name_1', 'name_2');
$array = array(
'name_1' => 'Alva',
'name_2' => 'Jack'
);
echo "$array[name_1]";//output Alva
echo "$array['name_1']";//parsing error using single or double quote in this situlation
?>
确切地说,在key上加单引号和双引号都是错误的。所以在string parse中处理数组情况,尽量使用"${}"和"{$}"模式,避免混乱。
===========================================================================
4.Object的处理。
对于属性,可以直接写,也可以加上"{}";
例如
<?php
class MyClass{
public $name;
public function __construct($name){
$this->name = $name;
}
public function getName(){
return $this->name;
}
}
$myclass = new MyClass('Alva');
echo "$myclass->name";//output Alva
echo "{$myclass->name}";//output Alva
?>
对于对象的动态方法,必须使用"{}"
例如
<?php
class MyClass{
public $name;
public function __construct($name){
$this->name = $name;
}
public function getName(){
return $this->name;
}
}
$myclass = new MyClass('Alva');
echo "$myclass->getName()";//output ()
echo "{$myclass->getName()}";//output Alva
?>
对于类的静态方法、变量以及常量
似乎无法直接解析。。
例如
<?php
error_reporting(E_ALL);
class MyClass{
const const_1 = 'const';
public static $static = 'static_2';
public static function static_func(){
return 'static_func';
}
}
echo "{$MyClass::const_1}";//won't work
echo "{MyClass::$static}";//won't work
echo "{$MyClass::static_func()}";//won't work
?>
如果大家有什么好方法,请PM下我,谢谢~!