note 113993 added to language.constants.predefined
| From: | skoobiedu at gmail dot com | Date: | Thu, 26 Dec 2013 22:58:25 +0000 |
| Subject: | note 113993 added to language.constants.predefined | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-198034@lists.php.net to get a copy of this message | ||
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.
----
Server IP: 72.52.91.14
Probable Submitter: 72.52.91.14
----
Manual Page -- http://php.net/manual/en/language.constants.predefined.php
Edit -- https://master.php.net/note/edit/113993
Del: integrated -- https://master.php.net/note/delete/113993/integrated
Del: useless -- https://master.php.net/note/delete/113993/useless
Del: bad code -- https://master.php.net/note/delete/113993/bad+code
Del: spam -- https://master.php.net/note/delete/113993/spam
Del: non-english -- https://master.php.net/note/delete/113993/non-english
Del: in docs -- https://master.php.net/note/delete/113993/in+docs
Del: other reasons-- https://master.php.net/note/delete/113993
Reject -- https://master.php.net/note/reject/113993
Search -- https://master.php.net/manage/user-notes.php