In this tutorial you will learn how to work with PHP magic constants.
What is Magic Constants
In the PHP constants chapter we’ve learned how to define and use constants in PHP script.
PHP moreover also provide a set of special predefined constants that change depending on where they are used. These constants are called magic constants. For example, the value of \_\_LINE\_\_ depends on the line that it’s used on in your script.
Magic constants begin with two underscores and end with two underscores. The following section describes some of the most useful magical PHP constants.
LINE
The \_\_LINE\_\_ constant returns the current line number of the file, like this:
<?php
echo "Line number " . __LINE__ . "<br>"; // Displays: Line number 2
echo "Line number " . __LINE__ . "<br>"; // Displays: Line number 3
echo "Line number " . __LINE__ . "<br>"; // Displays: Line number 4
?>
FILE
The \_\_FILE\_\_ constant returns full path and name of the PHP file that’s being executed. If used inside an include, the name of the included file is returned.
<?php
// Displays the absolute path of this file
echo "The full path of this file is: " . __FILE__;
?>
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:
<?php
// Displays the directory of this file
echo "The directory of this file is: " . __DIR__;
?>
FUNCTION
The \_\_FUNCTION\_\_ constant returns the name of the current function.
<?php
function myFunction(){
echo "The function name is - " . __FUNCTION__;
}
myFunction(); // Displays: The function name is - myFunction
?>
CLASS
The \_\_CLASS\_\_ constant returns the name of the current class. Here’s an example:
<?php
class MyClass
{
public function getClassName(){
return __CLASS__;
}
}
$obj = new MyClass();
echo $obj->getClassName(); // Displays: MyClass
?>
METHOD
The \_\_METHOD\_\_ constant returns the name of the current class method.
<?php
class Sample
{
public function myMethod(){
echo __METHOD__;
}
}
$obj = new Sample();
$obj->myMethod(); // Displays: Sample::myMethod
?>
NAMESPACE
The \_\_NAMESPACE\_\_ constant returns the name of the current namespace.
<?php
namespace MyNamespace;
class MyClass
{
public function getNamespace(){
return __NAMESPACE__;
}
}
$obj = new MyClass();
echo $obj->getNamespace(); // Displays: MyNamespace
?>
此处评论已关闭