PHP Quick Tip: use __DIR__ instead of dirname(__FILE__) from PHP 5.3PHP Quick Tip: use __DIR__ instead of dirname(__FILE__) from PHP 5.3

Posted May 13th, 2010 in PHP and Quick Tips

The traditional way of getting the directory the current file is in with PHP is to use dirname(__FILE__). From PHP 5.3 there is a new magic constant__DIR__ which is the equivilent of this function call.

__DIR__ magic constant

The __DIR__ magic constant is a "magic constant" which changes depending where it is used. It contains the directory of the file it is in. If the file is an include, it is the directory that include file is in. If it is the main script it is the directory that script is in.

__DIR__ is available from PHP 5.3 only. If prior versions a notice will be issued if it is used and the value will be __DIR__ and not the actual directory.

Example error if a version prior to PHP 5.3 is used:

Notice: Use of undefined constant __DIR__ - assumed '__DIR__' in ...

Unless your application requires the use of PHP 5.3 or greater, stick with the traditional use of:

dirname(__FILE__);

Related posts:

Comments

blog comments powered by Disqus