php的魔术变量
php手册里面的解释
__FUNCTION__ returns only the name of the function 返回的仅仅是函数的名称
__METHOD__ returns the name of the class alongwith the name of the function 返回的是函数的名称,如果取出class的方法名,而__METHOD__不光能取出方法名,还能取出class名
1 class trick
2 {
3 function doit()
4 {
5 echo __FUNCTION__;
6 }
7 function doitagain()
8 {
9 echo __METHOD__;
10 }
11 }
12 $obj=new trick();
13 $obj->doit();
14 //output will be ---- doit 输出doit
15 $obj->doitagain();
16 //output will be ----- trick::doitagain 输出 trick::doitagain
__CLASS__ 类的名称
get_class() 返回对象的类名 string get_class ([ object $obj ] ) 返回对象实例 obj 所属类的名字。如果 obj 不是一个对象则返回 FALSE
The __CLASS__ magic constant nicely complements the get_class() function. 魔术常量__CLASS__ 很好的补充了get_class()函数
Sometimes you need to know both: 有时候你会知道下面两个
- name of the inherited class 继承类的class 名称
- name of the class actually executed 实际执行的class 的名称
Here's an example that shows the possible solution: 下面是实例
1 <?php
2
3 class base_class
4 {
5 function say_a()
6 {
7 echo "'a' - said the " . __CLASS__ . "<br/>";
8 }
9
10 function say_b()
11 {
12 echo "'b' - said the " . get_class($this) . "<br/>";
13 }
14
15 }
16
17 class derived_class extends base_class
18 {
19 function say_a()
20 {
21 parent::say_a();
22 echo "'a' - said the " . __CLASS__ . "<br/>";
23 }
24
25 function say_b()
26 {
27 parent::say_b();
28 echo "'b' - said the " . get_class($this) . "<br/>";
29 }
30 }
31
32 $obj_b = new derived_class();
33
34 $obj_b->say_a();
35 echo "<br/>";
36 $obj_b->say_b();
37
38 ?>
输出的内容:
'a' - said the base_class
'a' - said the derived_class
'b' - said the derived_class
'b' - said the derived_class
__DIR__文件所在的目录。如果用在被包括文件中,则返回被包括的文件所在的目录。它等价于 dirname(__FILE__) (PHP 5.3.0中新增)
__FILE__ 文件的完整路径和文件名。如果用在被包含文件中,则返回被包含的文件名
如果你想使用在未定义__DIR__ 使用可以用如下方法:
<?php
//第一种方法:
if(!defined(‘__DIR__’)) {
$iPos = strrpos(__FILE__, “/”);
define(“__DIR__”, substr(__FILE__, 0, $iPos) . “/”);
}
//第二种方法:
function abspath($file)
{
return realpath(dirname($file));
}
abspath(__FILE__);
?>
__NAMESPACE__ 当前命名空间的名称(大小写敏感)。这个常量是在编译时定义的(PHP 5.3.0 新增)
__STATIC__ 当你调用class的静态方法时,返回class名称,区分大小写。如果在继承中调用的话,不管在继承中有没有定义,都能返回继承的class名。
__LINE__ 文件中的当前行号。
__TRAIT__ Trait 的名字(PHP 5.4.0 新加)。自 PHP 5.4 起此常量返回 trait 被定义时的名字(区分大小写)。Trait 名包括其被声明的作用区域(例如 Foo\Bar)。

浙公网安备 33010602011771号