PHP Magic Constants

There are currently seven variables in PHP that are dynamic and always set. They have come to be known as the Magic Constants.

What do I mean when I say dynamic? Well, although they are called constants, they are not. Say, what? With constants the generally accepted usage is that you don't change them once they are set, or else why would you call them constants.

The designers of PHP had a need for a multitude of information from within the code, while it was running. In the case of error messages, they wanted to output the file name and line number where an error occurred. The trouble with doing this is the information on line number, file name, directory, and namespace is always changing. It's dynamic information, and it needs to be constantly updated as you move around your application, or how else would the error message know the correct file and line number where an error occurred.

The PHP designers, in their infinite wisdom, created "Magic Constants." They act like constants in that they are always set, but they change dynamically depending where you are executing in your code. Let's take a look.

First, the seven magic constants are:

__LINE__ outputs the current line number in the file,

__FILE__ outputs the current file name,

__DIR__ outputs the current directory,

__FUNCTION__ outputs the current function being run,

__CLASS__ outputs the current class,

__METHOD__ outputs the current class method,

__NAMESPACE__ output the current namespace.

How do you use them?

First let's create an example program

The output of this code snippet looks like this:

In this example, you may have picked up that I didn't use the namespace. Namespaces are only supported on PHP 5.3 and above, which I'm not running at this time. Yes, I actually ran this code, it works, and the output is as shown.

The dashes before and after the constant name are double dashes, not single dashes. To help you write clearer code, like a constant, magic constants should be capitalized. It will work without capitalizing as I showed you in the __file__ example above, but it makes your code more difficult to read.

When you echo out the magic constant you don't need a $ in front of the constant. You do need the double dashes before and after the word, and the word, capitalized, please. Otherwise, treat magic constants just like variables.

The end result of all this, is that anytime you need the line number, file name, directory name, function, class, method, or namespace at that particular instance in your code, you have it, and can use it, just like you would use any other variable in your code. Enjoy.

Comments are closed.