note 113993 deleted from language.constants.predefined by peehaa

From: Date: Mon, 22 May 2017 07:27:49 +0000
Subject: note 113993 deleted from language.constants.predefined by peehaa
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-209089@lists.php.net to get a copy of this message
Note Submitter: skoobiedu at gmail dot com ---- What eyecatchup and I posted are good one-liners, but they are fundamentally flawed. Magic constants cannot be defined in a backward-compatible manner in PHP code because the value of a magic constant is defined at run-time based on the current context. __DIR__ is defined relative to the current file. If you define it in one file using the method that I or eyecatchup posted, then the value is dependant upon the location of the file where it is defined. Example: * directory structure: /dir/other/other_dir.php /dir/define_dir.php /dir/same_dir.php /parent_dir.php * /dir/define_dir.php <?php /** * Ensure the __DIR__ constant is defined for PHP 4.0.6 and newer. */ (@__DIR__ == '__DIR__') && define('__DIR__', realpath(dirname(__FILE__))); ?> * /dir/same_dir.php <?php require('define_dir.php'); echo 'function: ' . realpath(dirname(__FILE__)) . "\n"; echo ' __DIR__: ' . __DIR__ . "\n"; ?> * /dir/other/other_dir.php <?php require('../define_dir.php'); echo 'function: ' . realpath(dirname(__FILE__)) . "\n"; echo ' __DIR__: ' . __DIR__ . "\n"; ?> * /parent_dir.php <?php require('dir/define_dir.php'); echo 'function: ' . realpath(dirname(__FILE__)) . "\n"; echo ' __DIR__: ' . __DIR__ . "\n"; ?> *** OUTPUT: PHP 5.2.17 *** same_dir.php: function: /dir __DIR__: /dir other_dir.php: function: /dir/other __DIR__: /dir parent_dir.php: function: / __DIR__: /dir As you can see, only when the running script is in the same directory as the file that defines __DIR__, will __DIR__ have the correct value. You could use the following function: <?php function abspath($file) { return realpath(dirname($file)); } ?> And call it like so wherever you would use __DIR__: <?php abspath(__FILE__); ?> Magic constants are fickle creatures.

« previous php.notes (#209089) next »