note 29273 added to language.variables.scope
| From: | jg at rack1 dot php dot net | Date: | Fri, 07 Feb 2003 22:10:24 +0000 |
| Subject: | note 29273 added to language.variables.scope | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-43587@lists.php.net to get a copy of this message | ||
It's possible to use a variable variable when specifying a variable as global in a function.
That way your function can decide what global variable to access in run-time.
function func($varname)
{
global $$varname;
echo $$varname;
}
$hello = "hello world!";
func("hello");
This will print "hello world!", and is roughly the same as passing by reference, in the
case when the variable you want to pass is global. The advantage over references is that they
can't have default parameters. With the method above, you can do the following.
function func($varname = FALSE)
{
if ($varname === FALSE)
echo "No variable.";
else
{
global $$varname;
echo $$varname;
}
}
$hello = "hello world!";
func("hello"); // prints "hello world!"
func(); // prints "No variable."
--
http://www.php.net/manual/en/language.variables.scope.php
http://master.php.net/manage/user-notes.php?action=edit+29273
http://master.php.net/manage/user-notes.php?action=delete+29273
http://master.php.net/manage/user-notes.php?action=reject+29273