Magic Constants in PHP

PHP provides useful magic constants for fetching the current line number (__LINE__), file path (__FILE__), directory path (__DIR__), function name (__FUNCTION__), class name (__CLASS__), method name (__METHOD__) and namespace (__NAMESPACE__).
We are not going to cover each one of these in this article, but I will show you a few use cases.

// this is relative to the loaded script's path
// it may cause problems when running scripts from different directories
// this is always relative to this file's path
// no matter where it was included from
require_once(dirname(__FILE__) . '/config/database.php');


Using __LINE__ makes debugging easier. You can track down the line numbers:

// some code
// ...
my_debug("some debug message", __LINE__);
/* prints
Line 4: some debug message
// some more code
// ...
my_debug("another debug message", __LINE__);
/* prints
Line 11: another debug message
function my_debug($msg, $line) {
 echo "Line $line: $msg\n";

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s