Is using PHP define() within a function actually useful to the caller of that function?

constants, function, php, scope

Solution

The sample function works. The scope of a constant is global. However, the reason(s) to do this are dubious imho.

Problem

On the php.net manual page for `define()`, there's a user-contributed note that suggests that you can usefully call `define()` from within a function. Lightly paraphrasing, the suggestion is to create a function like this: ``` <?php function xdefine($a) { foreach($a as $k => $v) define($k, $v); } ?> ``` and then to subsequently use it like this: ``` <?php xdefine(array( "SECOND" => 1, "MINUTE" => 60, "HOUR" => 3600, "DAY" => 86400, "WEEK" => 604800, "MONTH" => 2592000, // 30 days month "YEAR" => 31536000, "LEAPYEAR" => 31622400 )); ?> ``` But both my sense and my experience are that this doesn't work: after the `xdefine()` call, each of the identifiers just evaluates to its own name, not to the value that `xdefine()` supposedly bound to it. The reason seems pretty obvious to me (i.e., because the symbols get their values as the module containing the call to `xdefine()` is being parsed/loaded), but maybe there's some subtlety I'm missing. The author of the post named his function something different, using a cute Unicode character, but I'm pretty sure that's just a cosmetic difference. (BTW, something similar does work for me if I don't define a function like `xdefine()`, but rather, just run the same `foreach()` loop over the contents of the array, provided that both the loop and the array are at module scope. This is also expected behavior, from my perspective.) So, can someone look at the original post and tell me if there's really anything to it? Or does the author just have it wrong? (I'd post this to the referenced php.net page, but I think I will get more eyes on the question faster if I post it here instead :-)

Original source