note 77068 added to function.define
| From: | eslindseyatgmaildotcom at osu1 dot php dot net | Date: | Mon, 13 Aug 2007 20:38:40 +0000 |
| Subject: | note 77068 added to function.define | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-129453@lists.php.net to get a copy of this message | ||
Constants can't be referenced from within quotes or (more importantly IMHO) from within HEREDOC
syntax. This is a huge drawback in my opinion. Here's two of my workarounds:
<?php
//PHP5 only -- more efficient
$constarray = get_defined_constants(true);
foreach($constarray['user'] as $key => $val)
eval(sprintf('$_CONSTANTS[\'%s\'] = \'%s\';', addslashes($key),
addslashes($val)));
//PHP4+ -- less efficient because it defines (potentially) hundreds of unnecessary constants
foreach(get_defined_constants() as $key => $val)
eval(sprintf('$_CONSTANTS[\'%s\'] = \'%s\';', addslashes($key),
addslashes($val)));
?>
Now you can refer to your defined constants using the $_CONSTANTS array. Note that because this is
NOT a superglobal, a few caveats apply:
<?php
//run code snippet here to define $_CONSTANTS in global scope...
$mv = $_CONSTANTS['FOO']; //works
function my_function1()
{
$mv = $_CONSTANTS['BAR']; //doesn't work! not defined!
}
function my_function2()
{
global $_CONSTANTS;
$mv = $_CONSTANTS['BAR']; //ah, this works!
}
?>
I realize this is not ideal, either for performance or for convenience of being able to refer to
constants without regard to scope, but it is a workaround that works. Depending on your application,
it may be easier to shift your paradigm a bit and use the following method instead, declaring your
constants as variables first:
<?php
//first, define our constants...
$_CONSTANTS['FOO'] = 'bar';
$_CONSTANTS['BAR'] = 'foo';
//now, turn them into real constants...
foreach($_CONSTANTS as $key => $val)
define($key, $val);
//now, you can use either format to refer to a constant
print($_CONSTANTS['FOO']); //prints 'bar'
print(FOO); //prints 'bar'
print("$_CONSTANTS['FOO']"); //prints 'bar'
//prints 'blah bar blah'
print <<<EOF
blah {$_CONSTANTS['FOO']} blah
EOF;
?>
Hope this helps some of you out there, I know being able to utilize my constants in HEREDOC helped
me a ton!
----
Server IP: 69.147.83.197
Probable Submitter: 70.43.179.174
----
Manual Page -- http://www.php.net/manual/en/function.define.php
Edit -- https://master.php.net/note/edit/77068
Del: integrated -- https://master.php.net/note/delete/77068/integrated
Del: useless -- https://master.php.net/note/delete/77068/useless
Del: bad code -- https://master.php.net/note/delete/77068/bad+code
Del: spam -- https://master.php.net/note/delete/77068/spam
Del: non-english -- https://master.php.net/note/delete/77068/non-english
Del: in docs -- https://master.php.net/note/delete/77068/in+docs
Del: other reasons-- https://master.php.net/note/delete/77068
Reject -- https://master.php.net/note/reject/77068
Search -- https://master.php.net/manage/user-notes.php