PHP: Magic constants

PHP: Magic constants

Constant is a name of simple value (number, text), which should not change during code execution. Constants are case sensitive, and good programming style requires use them in uppercase.

define("FOO",     "something");

During script execution large number of constants is available defined by php engine. For example,  M_PI (3.1415926535898).

Exception is magic constants which value depends on where they are requested [2].

Let us have a look at an example:

<?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__

he current line number of the file.

9

__FILE__

The full path and filename of the file.

/var/www/sample.php

__DIR__

The directory of the file. Equivalent dirname(__FILE__). Available since 5.3.0

__DIR__

__FUNCTION__

This constant returns the function name as it was declared.

test

__CLASS__

This constant returns the class name as it was declared.

Sample

__METHOD__

The method name is returned as it was declared. Available since 5.0.0

Sample::test

__NAMESPACE__

The name of the current namespace. Available since 5.3.0

__NAMESPACE__

 

By the way  __LINE__ is very useful detecting sql queries returning error. 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

» Rate it!

(5)

» Related articles

» Comments

No comments
* mandatory
* not public
Besucherzahler ukraina brides
website counter
vimeo youtube     myspace facebook twitter
where to eat in riga?