Research & Documentation 02 Magic Constants

PHP Magic Constants

What are Magic Constants?

Constants in PHP are similar to variables in that they are identifiers that are able to be assigned fixed values. Unlike variables, they cannot be changed or undefined once they are assigned. Magic constants, on the other hand, can change depending on where they are used in a script. Regular constants are resolved at runtime (the time at which executable code starts running), while magic constants are resolved at compile time (the time at which source code is converted into executable code).

MC 1: __LINE__

The __LINE__ constant returns the current line number of the file in which the constant is being used. The PHP file for this page contains the code echo __LINE__ on line 17, so the browser will display "17" below:

17

Because magic constants can change depending on their placement, another use of __LINE__ will display a different value if used on another line. Below, echo __LINE__ has been written on line 23 and will return the number "23":

23

MC 2: __FILE__

The __FILE__ constant returns the full path and filename of the current file used to display the web page. Using the code echo __FILE__, the browser displays:

/var/www/vhosts/toleary.bitweb1.nwtc.edu/httpdocs/php/rd/02-magic-constants.php

If this constant is written in an include, the code will return the path for the specific include file.

MC 3: __DIR__

The __DIR__ constant returns the directory of the current file. echo __DIR__ will tell the browser to display essentially the same information as __FILE__, minus the filename (and minus a trailing slash, unless the directory is the root directory), as shown below:

/var/www/vhosts/toleary.bitweb1.nwtc.edu/httpdocs/php/rd

Like __FILE__, if __DIR__ is written in an include, it will return the directory for the include file.

MC 4: __FUNCTION__

The __FUNCTION__ constant, when used inside a function, returns the name of said function. Below, I have created a function called returnFunction(), with a parameter of echo 'The name of the current function is: ' . __FUNCTION__;'. Calling returnFunction(); displays the following:

The name of the current function is: returnFunction

Resources