note 12841 modified in language.variables.variable by philip
| From: | philip@php.net | Date: | Wed, 16 Mar 2005 01:36:38 +0000 |
| Subject: | note 12841 modified in language.variables.variable by philip | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-86512@lists.php.net to get a copy of this message | ||
Variable variables techniques do not work when one of the "variables" is a constant. The
example below illustrates this. This is probably the desired behavior for constants, but was
confusing for me when I was trying to figure it out. The alternative I used was to add the
variables I needed to the $GLOBALS array instead of defining them as constants.
<?php
define("DB_X_NAME","database1");
define("DB_Y_NAME","database2");
$DB_Z_NAME="database3";
function connectTo($databaseName){
global $DB_Z_NAME;
$fullDatabaseName="DB_".$databaseName."_NAME";
return ${$fullDatabaseName};
}
print "DB_X_NAME is ".connectTo("X")."<br>";
print "DB_Y_NAME is ".connectTo("Y")."<br>";
print "DB_Z_NAME is ".connectTo("Z")."<br>";
?>
[Editor Note: For variable constants, use constant() --Philip]
--was--
Variable variables techniques do not work when one of the "variables" is a constant. The
example below illustrates this. This is probably the desired behavior for constants, but was
confusing for me when I was trying to figure it out. The alternative I used was to add the
variables I needed to the $GLOBALS array instead of defining them as constants.
<?php
define("DB_X_NAME","database1");
define("DB_Y_NAME","database2");
$DB_Z_NAME="database3";
function connectTo($databaseName){
global $DB_Z_NAME;
$fullDatabaseName="DB_".$databaseName."_NAME";
return "\"".${$fullDatabaseName}."\"";
}
print "DB_X_NAME is ".connectTo("X")."<br>";
print "DB_Y_NAME is ".connectTo("Y")."<br>";
print "DB_Z_NAME is ".connectTo("Z")."<br>";
?>
http://php.net/manual/en/language.variables.variable.php