note 29273 modified in language.variables.scope by danbrown

From: Date: Mon, 18 May 2009 01:41:59 +0000
Subject: note 29273 modified in language.variables.scope by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-155580@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. <?php 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. <?php 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." ?> --was-- 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://php.net/manual/en/language.variables.scope.php

« previous php.notes (#155580) next »