PHP Magic constants

Spread the love

In the PHP constants chapter we’ve learned how to define and use constants in PHP script.

PHP provides a large number of predefined constants to any script which it runs.

There are five magical constants that change depending on where they are used. For example, the value of __LINE__ depends on the line that it’s used on in your script. These special constants are case-insensitive and are as follows −

A few “magical” PHP constants are given below −

1) __LINE__

The __LINE__ constant returns the current line number of the file, like this:

2) __FILE__

The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, __FILE__always contains an absolute path whereas in older versions it contained relative path under some circumstances.

3) __DIR__

The __DIR__ constant returns the directory of the file. If used inside an include, the directory of the included file is returned. Here’s an example:

4) __FUNCTION__

The __FUNCTION__ constant returns the name of the current 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.

5) __CLASS__

The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.

5) __METHOD__

The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive).

 

You may also like...

3 Responses

  1. October 28, 2018

    […] Magic Constant Magic Constant […]

  2. October 28, 2018

    […] Magic Constant Magic Constant […]

  3. October 28, 2018

    […] PHP Coding StandardsMagic Constant […]

Leave a Reply

Your email address will not be published. Required fields are marked *