您好,欢迎访问一九零五行业门户网

PHP中什么是魔术常量?有哪些魔术常量?(总结)

之前我们已经了解了一些常用的魔术方法,除了魔术方法外,php还提供一些魔术常量,相信大家在日常的工作中也都使用过,这里给大家做一个总结。
其实php还提供了很多常量但都依赖于各类扩展库,而有几个常量是通用并且是跟随它们所在代码的位置来提供一些与位置有关的信息,这些就是***魔术常量***。
魔术常量是不分大小写的,__line__和__line__是一样的,但对于工程化的开发来说,常量还是尽量以大写为主。
__line__
文件中的当前行号。
echo __line__ . php_eol; // 3function testline(){ echo __line__ . php_eol; // 7}class testlineclass{ function testline() { echo __line__ . php_eol; // 14 }}testline();$test = new testlineclass();$test->testline();
__file__
文件的完整路径和文件名。如果用在被包含文件中,则返回被包含的文件名。自 php 4.0.2 起,__file__ 总是包含一个绝对路径(如果是符号连接,则是解析后的绝对路径),而在此之前的版本有时会包含一个相对路径。
echo __file__ . php_eol; // d:\phpproject\php\newblog\php-magic-constant.php
__dir__
文件所在的目录。如果用在被包括文件中,则返回被包括的文件所在的目录。它等价于 dirname(__file__)。除非是根目录,否则目录中名不包括末尾的斜杠。(php 5.3.0中新增) =
echo __dir__ . php_eol; // d:\phpproject\php\newblog
__function__
函数名称(php 4.3.0 新加)。自 php 5 起本常量返回该函数被定义时的名字(区分大小写)。在 php 4 中该值总是小写字母的。
echo __function__ . php_eol; // 啥都没输出function testfunction(){ echo __function__ . php_eol; // testfunction}class testfunctionclass{ function testfunction1() { echo __function__ . php_eol; // testfunction1 }}testfunction();$test = new testfunctionclass();$test->testfunction1();
__class__
类的名称(php 4.3.0 新加)。自 php 5 起本常量返回该类被定义时的名字(区分大小写)。在 php 4 中该值总是小写字母的。类名包括其被声明的作用区域(例如 foo\bar)。注意自 php 5.4 起 __class__ 对 trait 也起作用。当用在 trait 方法中时,__class__ 是调用 trait 方法的类的名字。
echo __class__ . php_eol; // 什么也没有function testclass(){ echo __class__ . php_eol; // 什么也没有}trait testclasstrait{ function testclass2() { echo __class__ . php_eol; // testclassclass }}class testclassclass{ use testclasstrait; function testclass1() { echo __class__ . php_eol; // testclassclass }}testclass();$test = new testclassclass();$test->testclass1();$test->testclass2();
__trait__
trait 的名字(php 5.4.0 新加)。自 php 5.4 起此常量返回 trait 被定义时的名字(区分大小写)。trait 名包括其被声明的作用区域(例如 foo\bar)。
echo __trait__ . php_eol; // 什么也没有function testtrait(){ echo __trait__ . php_eol; // 什么也没有}trait testtrait{ function testtrait2() { echo __trait__ . php_eol; // testtrait }}class testtraitclass{ use testtrait; function testtrait1() { echo __trait__ . php_eol; // 什么也没有 }}testtrait();$test = new testtraitclass();$test->testtrait1();$test->testtrait2();
__method__
类的方法名(php 5.0.0 新加)。返回该方法被定义时的名字(区分大小写)。
echo __method__ . php_eol; // 什么也没有function testmethod(){ echo __method__ . php_eol; // testmethod}class testmethodclass{ function testmethod1() { echo __method__ . php_eol; // testmethodclass::testmethod1 }}testmethod();$test = new testmethodclass();$test->testmethod1();
__namespace__
当前命名空间的名称(区分大小写)。此常量是在编译时定义的(php 5.3.0 新增)。
echo __namespace__ . php_eol; // test\magic\constantclass testnamespaceclass{ function testnamespace() { echo __namespace__ . php_eol; // test\magic\constant }}$test = new testnamespaceclass();$test->testnamespace();
完整代码:https://github.com/zhangyue0503/php/blob/master/newblog/php-magic-constant.php
推荐学习:《php视频教程》
以上就是php中什么是魔术常量?有哪些魔术常量?(总结)的详细内容。
其它类似信息

推荐信息