PHP Magic Constants

Table of Contents

Magic Constants

Here are the magic constants, with descriptions and examples:

Constant Description
__CLASS__ If used inside a class, the class name is returned.
__DIR__ The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory.
__FILE__ The full path and filename of the file. If used inside an include, the name of the included file is returned.
__FUNCTION__ The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
__LINE__ The current line number of the file.
__METHOD__ The class method name.
__NAMESPACE__ The name of the current namespace. (Added in PHP 5.3.0)

PHP 1 MagicConstant CLASS

<h2>phpMagicConstant __CLASS__ </h2> <p>If used inside a class, the class name is returned </p> <?php class Fruits { public function myValue() { return __CLASS__; } } $kiwi = new Fruits(); echo $kiwi->myValue(); ?>

Example 1

Result View Example

PHP 2 MagicConstant DIR

<h2>phpMagicConstant__DIR__</h2> <p>The directory of the file.</p> <?php echo __DIR__; ?>

Example 2

Result View Example

PHP 3 MagicConstant FILE

<h2>phpMagicConstant-__FILE__</h2> <p>The file name including the full path.</p> <?php echo __FILE__; ?>

Example 3

Result View Example

PHP 4 MagicConstant FUNCTION

<h2>phpMagicConstant-__FUNCTION__</h2> <p>If inside a function, the function name is returned.</p> <?php function myValue(){ return __FUNCTION__; } echo myValue(); ?>

Example 4

Result View Example

PHP 5 MagicConstant LINE

<h2>phpMagicConstant-__LINE__</h2> <p>The current line number.</p> <?php echo __LINE__; ?>

Example 5

Result View Example

Document

Document in project

You can Download PDF file.

Reference