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)。 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM