note 113233 added to language.constants.predefined

From: Date: Mon, 16 Sep 2013 10:09:00 +0000
Subject: note 113233 added to language.constants.predefined
Groups: php.notes 
Request: Send a blank email to php-notes+get-196267@lists.php.net to get a copy of this message
As pointed out by david at thegallagher dot net[1], you can NOT use the defined() function to check if a *magic* constant is defined. Often seen, but will not work: <?php if (!defined('__MAGIC_CONSTANT__')) { // FAIL! even if __MAGIC_CONSTANT__ is defined, // defined('__MAGIC_CONSTANT__') will ALWAYS return (bool)false. } ?> Now, raat1979 at gmail dot com[2] pointed out a solution to check if a magic constant is defined or not (which actually works reliable). Thanks to dynamic typecasting in PHP, if a constant lookup fails PHP interprets the given constant name as string (note that a notice is thrown nonetheless. thus, use "@" to suppress it). <?php var_dump(@UNDEFINED_CONSTANT_NAME); //prints: string(23) "UNDEFINED_CONSTANT_NAME" ?> Meaning we can check for all constants - including magic constants (eg __DIR__) - as follows: <?php if (@__DIR__ == '__DIR__'){ // __DIR__ was interpreted as string. thus, (magic) constant __DIR__ is not defined. } ?> However, what is wrong in raat1979 at gmail dot com's note[2] is this comment: > "remember that because they are MAGIC constants defining __DIR__ is completely > useless" In fact, you *can* define magic constants (as long as they haven't been defined before, of course). Based on all I've read and tested today, here is my code I use to make the __DIR__ magic constant work with all PHP versions (4.3.1 - 5.5.3): <?php // Ensure that PHP's magic constant __DIR__ is defined - no matter of the PHP version. // If magic __DIR__ constant is not defined, define it. (@__DIR__ == '__DIR__') && define('__DIR__', dirname(__FILE__)); // All PHP versions (>= 4.3.1) can use the magic __DIR__ constant now.. // Demo (outputs and VLD opcodes) here: http://3v4l.org/bm6e1 ?> [1] http://us2.php.net/manual/en/language.constants.predefined.php#107614 [2] http://us2.php.net/manual/en/language.constants.predefined.php#113130 ---- Server IP: 69.147.83.199 Probable Submitter: 80.187.100.217 (proxied: 13.76.38.221) ---- Manual Page -- http://php.net/manual/en/language.constants.predefined.php Edit -- https://master.php.net/note/edit/113233 Del: integrated -- https://master.php.net/note/delete/113233/integrated Del: useless -- https://master.php.net/note/delete/113233/useless Del: bad code -- https://master.php.net/note/delete/113233/bad+code Del: spam -- https://master.php.net/note/delete/113233/spam Del: non-english -- https://master.php.net/note/delete/113233/non-english Del: in docs -- https://master.php.net/note/delete/113233/in+docs Del: other reasons-- https://master.php.net/note/delete/113233 Reject -- https://master.php.net/note/reject/113233 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#196267) next »