12

New magic constant in PHP 5.3

published on 2008|02|22

In PHP 5.3 there will be another magic constant __DIR__. Until 5.3 a typical pattern to include files was to do something like this:

<?php
require_once dirname(__FILE__) . '/path/to/include.inc.php';

The extra dirname()-call will be gratuitous:

<?php
require_once __DIR__ . '/path/to/include.inc.php';

__DIR__ always references the directory which contains the current file. In case of /var/www/host/app/foo.php the __DIR__ will reference /var/www/host/app.
To allow this, the internal function php_dirname() has been moved in the Zend Engine and is now called zend_dirname(). Nevertheless an alias still exists.

Comments

Show comments linear or threaded

Paul M opines:
published on 2008|02|22, 10:27h
*

Good addons. I like it.

Toby reckons:
published on 2008|02|22, 10:42h
*

I’ve been waiting for this for a long, long time. :)

bapro responses:
published on 2008|02|22, 12:57h
*

Little but nice change.

Andre Moelle responses:
published on 2008|02|22, 14:42h
*

Something I really missed so far. ;-)

Stuart Herbert responses:
published on 2008|02|23, 12:30h
*

What will the value of DIR be if the path to the current file contains a symlink? Will DIR contain the smylink, or will it be more like realpath(dirname(__FILE__))?

Lars Strojny opines:
published on 2008|02|23, 13:49h
*

Internally it is implemented exactly as dirname(__FILE__). If /tmp/bar is a symlink to /tmp/foo and /tmp/foo/baz.php does something with the constant the value will be /tmp/foo whether it is executed as /tmp/foo/baz.php or /tmp/bar/baz.php.

Stuart Herbert states:
published on 2008|02|23, 16:04h
*

Hrm. You’d really want the symlink to be honoured. Shame.

Lars Strojny means:
published on 2008|02|23, 21:11h
*

I’m not really sure if it would be a good thing to change the behaviour. I mean, what would be the benefit?

NikoB supposes:
published on 2008|09|26, 21:48h
*

This is very useful for some people. We need to run the same code from different symlinks to the same directory and this is not possible because symlinks are resolved. There is no way to tell if the script was called from a symlink, and which one. This is especially true in included files, where $_SERVER[‘SCRIPT_FILENAME’] returns the path to the calling script (and not the included one, obviously, since httpd doesn’t call the include directly, it’s PHP’s job).

BlazS answers:
published on 2008|02|25, 08:57h
*

isn’t the require_once ‘./baz.php’ the same ?

Lars Strojny reckons:
published on 2008|02|25, 09:24h
*

Question of the day: which file does “./baz.php” reference if “bar.php”, the file which contains that directive, is included by “foo.php” one directory above?

BlazS reckons:
published on 2008|02|25, 09:33h
*

My mistake :P

Add comment


Textile-formatting allowed
E-Mail addresses will not be displayed and will only be used for E-Mail notifications
Pavatar/Gravatar/Favatar/MyBlogLog author images supported.