note 103806 added to function.define
| From: | ionut dot botizan at yahoo dot com | Date: | Wed, 04 May 2011 15:59:39 +0000 |
| Subject: | note 103806 added to function.define | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-179420@lists.php.net to get a copy of this message | ||
@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
----
Server IP: 69.147.83.197
Probable Submitter: 86.122.168.37
----
Manual Page -- http://www.php.net/manual/en/function.define.php
Edit -- https://master.php.net/note/edit/103806
Del: integrated -- https://master.php.net/note/delete/103806/integrated
Del: useless -- https://master.php.net/note/delete/103806/useless
Del: bad code -- https://master.php.net/note/delete/103806/bad+code
Del: spam -- https://master.php.net/note/delete/103806/spam
Del: non-english -- https://master.php.net/note/delete/103806/non-english
Del: in docs -- https://master.php.net/note/delete/103806/in+docs
Del: other reasons-- https://master.php.net/note/delete/103806
Reject -- https://master.php.net/note/reject/103806
Search -- https://master.php.net/manage/user-notes.php