超越PHP PHP动态 | 经典文章 | CLASS | 相关下载 | 常见问题 | FORUM | WIKI | 在线手册
Site search:    
<变量范围PHP 的外部变量>
Last updated: Fri, 22 Jun 2007

可变变量

有时候使用可变变量名是很方便的。就是说,一个变量的变量名可以动态的设置和使用。一个普通的变量通过声明来设置,例如:

<?php
$a
= "hello";
?>

一个可变变量获取了一个普通变量的值作为这个可变变量的变量名。在上面的例子中 hello 使用了两个美元符号($)以后,就可以作为一个可变变量的变量了。例如:

<?php
$$a = "world";
?>

这时,两个变量都被定义了:$a 的内容是“hello”并且 $hello 的内容是“world”。因此,可以表述为:

<?php
echo "$a ${$a}";
?>

以下写法更准确并且会输出同样的结果:

<?php
echo "$a $hello";
?>

它们都会输出:hello world

要将可变变量用于数组,必须解决一个模棱两可的问题。这就是当写下 $$a[1] 时,解析器需要知道是想要 $a[1] 作为一个变量呢,还是想要 $$a 作为一个变量并取出该变量中索引为 [1] 的值。解决此问题的语法是,对第一种情况用 ${$a[1]},对第二种情况用 ${$a}[1]

注意可变变量不能用于 PHP 的超全局变量数组。这意味着不能这样用:${$_GET}。 如果想要一种处理超全局变量和老的 HTTP_*_VARS 的方法,应该尝试引用它们。




add a note add a note User Contributed Notes
可变变量
terry at terrym dot com
03-Aug-2000 10:01
Hello

(I guess pre tags are broken, but will use them anyway incase they get fixed.)

The most important useage of veriable veriable that I have found is not even mentioned here.

That is, function veriables:

$funcvar="my_formdatafunc";
$$funcvar(); // calls the function w/no parameters.
${$funcvar( $var1, "string", $nutervar)}; // w/parameters

I've been using this undocumented feature for some time and only just now realized that it is undocumented.
It is most usefull with form data processing to handle multiple forms with one script and such.
Where $funcvar my be the name of a database table used as a function name.

Terry Mackintosh <terry@terrym.com>

<变量范围PHP 的外部变量>
 Last updated: Fri, 22 Jun 2007
view source | feedback | send page | sitemap | aboutus   
Copyright ® 2002-2003 PHPE.NET. All rights reserved
Last updated:2002-11-22