Magic Constants in PHP
Magic Constants
Magic constants are the
predefined constants in PHP which get changed on the basis of their use. They
start with double underscore (__) and ends with double underscore.
They are similar to other
predefined constants but as they change their values with the context, they are
called magic constants.
There are nine magic
constants in PHP. In which eight magic constants start and end with double
underscores (__).
- __LINE__
- __FILE__
- __DIR__
- __FUNCTION__
- __CLASS__
- __TRAIT__
- __METHOD__
- __NAMESPACE__
- ClassName::class
1. __LINE__
v It returns the current line
number of the file, where this constant is used.
2. __FILE__:This magic constant returns
the full path of the executed file, where the file is stored. If it is used
inside the include, the name of the included file is returned.
3. __DIR__:
v
It
returns the full directory path of the executed file.
v
The
path returned by this magic constant is equivalent to dirname(__FILE__).
v
This
magic constant does not have a trailing slash unless it is a root directory.
4. __FUNCTION__:
v
This
magic constant returns the function name, where this constant is used.
v
It
will return blank if it is used outside of any function.
5. __CLASS__:
v
It
returns the class name, where this magic constant is used. __CLASS__ constant
also works in traits.
6. __TRAIT__:
v
This
magic constant returns the trait name, where it is used.
7. __METHOD__:
v
It
returns the name of the class method where this magic constant is included.
v
The
method name is returned the same as it was declared.
8. __NAMESPACE__:
v
It
returns the current namespace where it is used.
9. ClassName::class:
v
This
magic constant does not start and end with the double underscore (__).
v
It
returns the fully qualified name of the ClassName.
v
ClassName::class
is added in PHP
5.5.0. It is useful with namespaced classes.
Example:
<?php
namespace clg;
trait exe
{
function kbn()
{
echo "<br>trait is ",__trait__;
}
}
class Sam
{
use exe;
function display()
{
echo "Line number is ",__line__;
echo "<br>File is ",__file__;
echo "<br>Method is ",__method__;
echo "<br>Class is ",__class__;
echo "<br>Example for namespace ",__namespace__;
echo "<br>Function name is ",__function__;
echo "<br>Line is ",__line__;
}
}
$a=new Sam;
$a->display();
$a->kbn();
?>
Comments
Post a Comment