PHP Magic Constants
A constant is an identifier for a simple value (number, text) that cannot be changed during script execution. Constants are case-sensitive and by convention are written in uppercase. Alongside many constants automatically available during script execution, there are also "magic" constants whose value depends on where they are read.
A constant is an identifier for a simple value (number, text) that cannot be changed during script execution. Constants are case-sensitive and by convention are written in uppercase.
define("FOO", "something");
During PHP script execution, a bunch of pre-defined constants are available. For example: M_PI (3.1415926535898). The full list can be viewed here [1].
The exception is "magic" constants, whose value depends on where they are used [2].
Let us look at an example and what values each constant returns:
<?php
$s = new Sample;
$s->test(123);
class Sample {
function test($arg) {
echo __LINE__ . "<br>";
echo __FILE__ . "<br>";
echo __DIR__ . "<br>";
echo __FUNCTION__ . "<br>";
echo __CLASS__ . "<br>";
echo __METHOD__ . "<br>";
echo __NAMESPACE__ . "<br>";
}
}
|
Constant |
Description |
Value |
|
PHP_VERSION |
|
5.2.6 |
|
__LINE__ |
Line number in the PHP file |
9 |
|
__FILE__ |
Full file path. If used in an included file, the full path of that file. |
/var/www/sample.php |
|
__DIR__ |
The working directory containing the file. Equivalent to dirname(__FILE__). Added since 5.3.0 |
__DIR__ |
|
__FUNCTION__ |
Shows the function from which the constant is called. |
test |
|
__CLASS__ |
Shows the name of the class in which the constant is called. |
Sample |
|
__METHOD__ |
Class method name. Added since 5.0.0 |
Sample::test |
|
__NAMESPACE__ |
Namespace name. Added since 5.3.0 |
__NAMESPACE__ |
Incidentally, __LINE__ is useful for tracking down erroneous SQL queries. For example:
$sql = 'SELECT * FROM nothing';
$result = mysql_query($sql) or die(mysql_error() . ' /
#' . __LINE__ . ', ' . __FILE__ . '<pre>' . $sql . '</pre>');
Result:
No database selected / #15, /var/www/sample.php
SELECT * FROM nothing
Sources used:
1. http://www.php.net/manual/en/reserved.constants.php
2. http://www.php.net/manual/en/language.constants.predefined.php
comments