note 77067 deleted from function.get-defined-constants by joey
| From: | joey@php.net | Date: | Sun, 20 Jan 2013 08:53:28 +0000 |
| Subject: | note 77067 deleted from function.get-defined-constants by joey | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-193277@lists.php.net to get a copy of this message | ||
Note Submitter: eslindsey AT gma il dot co m
----
If you need to use the values of your defined constants in strings or for example in HEREDOC syntax,
use this function:
<?php
//PHP5+ only
$constarray = get_defined_constants(true);
foreach($constarray['user'] as $key => $val)
eval(sprintf('$_CONSTANTS[\'%s\'] = \'%s\';', addslashes($key),
addslashes($val)));
//PHP4+ ...this is less efficient since it defines hundreds of constants
foreach(get_defined_constants() as $key => $val)
eval(sprintf('$_CONSTANTS[\'%s\'] = \'%s\';', addslashes($key),
addslashes($val)));
?>
Once you run that you can use $_CONSTANTS['constantname'] to get the value of a constant.
You'll need to erase the array and rerun the code if you define any new constants. But I found
it handy when I wanted to use a couple of my defined constants in HEREDOC syntax. Don't forget:
because this is not really a superglobal you'll need to globalize it if you want to use it from
within a different scope, for example:
<?php
//hopefully you ran the snippet out here so that $_CONSTANTS is in global scope.
$mv = $_CONSTANTS['foo']; //works
function my_function()
{
global $_CONSTANTS; //without this line it won't work in here!
$mv = $_CONSTANTS['bar']; //works thanks to previous line
}
?>