Magic constants are predefined constants in PHP that can change depending on where they are used. This article will introduce you to PHP magic constants and introduce some commonly used PHP magic constants. I hope it will be helpful to you.
Magic constants start with two underscores (__) and end with two underscores (__). Below we will introduce some commonly used PHP magic constants.
__LINE__
__LINE__ constant returns the current line number of the file. Example:
<?php header("content-type:text/html;charset=utf-8"); echo "当前行数:" . __LINE__ . "<br>"; // 第3行 echo "当前行数:" . __LINE__ . "<br>"; // 第4行 echo "当前行数:" . __LINE__ . "<br>"; // 第5行 ?>
Output:
__FILE__
__FILE__ constant return is The full path and name of the PHP file being executed; if used within an include, returns the name of the included file.
<?php header("content-type:text/html;charset=utf-8"); // 显示此文件的绝对路径 echo "此文件的完整路径是: " . __FILE__; ?>
Output:
__DIR__
__DIR__ constant returns the directory of the file . If used within an include, returns the directory containing the file. Example:
<?php header("content-type:text/html;charset=utf-8"); // 显示此文件的目录 echo "此文件的目录是: " . __DIR__; ?>
Output:
##__FUNCTION__
## The #__FUNCTION__ constant returns the name of the current function. Example:
<?php header("content-type:text/html;charset=utf-8"); function myFunction(){ echo "函数名是:" . __FUNCTION__; } myFunction(); ?>
Output:
__CLASS__ Constant returns the name of the current class.
<?php header("content-type:text/html;charset=utf-8"); class MyClass { public function getClassName(){ return __CLASS__; } } $obj = new MyClass(); echo $obj->getClassName(); ?>
__METHOD__ constant return The name of the current class method.
<?php header("content-type:text/html;charset=utf-8"); class Sample { public function myMethod(){ echo __METHOD__; } } $obj = new Sample(); $obj->myMethod(); ?>
__NAMESPACE__constant return The name of the current namespace.
<?php // 定义代码在 'MyNamespace' 命名空间中 namespace MyNamespace; class MyClass { public function getNamespace(){ return __NAMESPACE__; } } $obj = new MyClass(); echo $obj->getNamespace(); // Displays: MyNamespace ?>
The above is the entire content of this article, I hope it will be helpful to everyone's learning. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !
The above is the detailed content of What are magic constants in PHP. For more information, please follow other related articles on the PHP Chinese website!