note 77067 added to function.get-defined-constants

From: Date: Mon, 13 Aug 2007 20:12:33 +0000
Subject: note 77067 added to function.get-defined-constants
Groups: php.notes 
Request: Send a blank email to php-notes+get-129452@lists.php.net to get a copy of this message
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 } ?> ---- Server IP: 69.147.83.197 Probable Submitter: 70.43.179.174 ---- Manual Page -- http://www.php.net/manual/en/function.get-defined-constants.php Edit -- https://master.php.net/note/edit/77067 Del: integrated -- https://master.php.net/note/delete/77067/integrated Del: useless -- https://master.php.net/note/delete/77067/useless Del: bad code -- https://master.php.net/note/delete/77067/bad+code Del: spam -- https://master.php.net/note/delete/77067/spam Del: non-english -- https://master.php.net/note/delete/77067/non-english Del: in docs -- https://master.php.net/note/delete/77067/in+docs Del: other reasons-- https://master.php.net/note/delete/77067 Reject -- https://master.php.net/note/reject/77067 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#129452) next »