note 103806 deleted from function.define by danbrown
| From: | danbrown@php.net | Date: | Wed, 04 May 2011 16:09:41 +0000 |
| Subject: | note 103806 deleted from function.define by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-179421@lists.php.net to get a copy of this message | ||
Note Submitter: ionut dot botizan at yahoo dot com
----
@andreas at cap-systems dot com
Don't do that!
And here's why:
<?php
define(FOO, 'BAR'); // triggers "Notice: Use of undefined constant FOO - assumed
'FOO' in..."
define(FOO, 'BAZ'); // this works (as it should!)
echo FOO; // echoes "BAR"
echo constant(FOO); // echoes "BAZ"
// the same as
echo BAR; // echoes "BAZ"
?>
What happens is that the first time, since FOO is not defined, it's evaluated to the string
"FOO" and gets defined.
The second call to define will evaluate the value of the previously defined constant FOO to
"BAR" and will define the constant BAR with the "BAZ" value.
This is also the reason why using unquoted array keys can get you in trouble:
<?php
$foo = array('bar' => 1, 'baz' => 2);
echo $foo['bar']; // echoes 1
echo $foo[bar]; // echoes 1
define('bar', 'baz');
echo $foo['bar']; // echoes 1
echo $foo[bar]; // echoes 2 - $foo[bar] is now equivalent to $foo['baz']
?>
The first time, since the
bar constant is undefined, it's evaluated to the string
"bar" and will return the expected result.
After the constant bar is defined, it will be evaluated to the string "baz"
and return the other array key