note 77068 deleted from function.define by cmb

From: Date: Sun, 06 Oct 2019 07:46:06 +0000
Subject: note 77068 deleted from function.define by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-212465@lists.php.net to get a copy of this message
Note Submitter: e s lin d sey at g mail dot co m ---- 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!

« previous php.notes (#212465) next »