php 魔術方法總結(持續更新)

來源:互聯網
上載者:User

標籤:php   魔術方法   

類中的魔術方法

PHP 魔術方法指的是在某些時刻會自動被調用的內建函數,它們以兩個連續的底線開頭。

類中的魔術方法__construct()

類的建構函式,用於初始化對象,在對象執行個體化時自動運行

__destruct()

解構函式,用於在 php 運行終止時,釋放對象所佔用的記憶體。解構函式是 php 的記憶體回收機制,使用棧結構,後進先出。

建構函式和解構函式的例子
class computer{    private $brand;    function __construct($brand){        $this->brand = $brand;    }    function __destruct(){        echo "release ".$this->brand."<br>";    }}$myComputer = new computer("MAC");$yourComputer = new computer("Asus");$hisComputer = new computer("Dell");echo "end of php file<br>";

輸出結果如下所示

end of php filerelease Dellrelease Asusrelease MAC

可以發現解構函式在 php 檔案執行結束之後才執行

__get($name)

類中用 protected 和 private 關鍵字定義的成員屬性或方法是無法通過對象的執行個體訪問的。__get() 方法會且僅會在對象的執行個體訪問 proctected 和 private 成員屬性 時自動執行 (訪問成員方法時不會,因為沒有意義)。

__get() 方法的意義在於將 proctected 和 private 成員屬性進行處理後輸出。

__get() 有且僅有一個輸入參數

__get() 方法的一個例子
class computer{    private $brand;    protected $owner;    public $price;    function __construct($brand, $owner, $price){        $this->brand = $brand;        $this->owner = $owner;        $this->price = $price;    }    function __get($name){        echo "It‘s up to me to decide if let you konw the owner and the brand of this computer or not :)<br>";        echo "I will tell you the name of woner: ".$this->owner."<br>";        echo "I won‘t tell you that the brand is ".md5($this->brand)."<br>";        echo "<br>";    }    function __destruct(){        echo "release ".$this->brand."<br>";    }}$myComputer = new computer("MAC", "me", "1000");$yourComputer = new computer("Asus", "you", "500");$hisComputer = new computer("Dell", "his", "700");echo $myComputer->price; echo "<br><br>";echo $myComputer->owner;echo $yourComputer->brand;echo "end of php file<br>";

輸出如下

1000It‘s up to me to decide if let you konw the owner and the brand of this computer or not :)I will tell you the name of woner: meI won‘t tell you that the brand is 2e25c285356cbb0ed8785a1377027d79It‘s up to me to decide if let you konw the owner and the brand of this computer or not :)I will tell you the name of woner: youI won‘t tell you that the brand is cb6ab3315634a1e4d11b091ba48b60baend of php filerelease Dellrelease Asusrelease MAC

可以看到,當訪問 public 成員屬性 price 時,__get()方法並沒有被調用。輸出 brand 時,我們使用了 md5 對其進行了加密處理,這種對封裝的成員屬性進行處理後輸出的用法就是 get 方法的意義所在。

__set($name, $value)

__set($name, $value) 與用於給當前類中封裝的方法或屬性進行重新賦值或定義。

與 get 類似但不同的時,__set($name, $value)會在成員屬性被訪問賦值時自動執行,其中 $name 是被訪問的成員屬性名,$value 為成員屬性被賦予的值

__set() 的例子
class computer{    private $brand;    protected $owner;    function __construct($brand, $owner, $price){        $this->brand = $brand;        $this->owner = $owner;        $this->price = $price;    }    function __get($name){        echo "It‘s up to me to decide if let you konw the owner and the brand of this computer or not :)<br>";        echo "I will tell you the name of woner: ".$this->owner."<br>";        echo "I won‘t tell you that the brand is ".md5($this->brand)."<br>";        echo "<br>";    }    function __set($name, $value){        $this->owner = $value;        echo "set $name to $value"."<br><br>";    }    function __destruct(){        echo "release ".$this->brand."<br>";    }}$myComputer = new computer("MAC", "me", "1000");echo $myComputer->owner = "my friend";echo $myComputer->owner;echo "end of php file<br>";

輸出結果

set owner to my friendmy friendIt‘s up to me to decide if let you konw the owner and the brand of this computer or not :)I will tell you the name of woner: my friendI won‘t tell you that the brand is 2e25c285356cbb0ed8785a1377027d79end of php filerelease MAC

我們看到在給 owner 賦值時調用了 set , 而訪問屬性時,調用了 get 。

__tostring()

用於直接列印物件控點,也就是說當我們使用 echo 加對象名時,__torsring()將會被自動調用

__tosring() 例子
class computer{    function __tostring(){        return "This is a computer class";    }}$myComputer = new computer();echo $myComputer;

如果沒有 __totring() 方法,我們是無法使用 echo+對象名,會出現 fatal error

__call($method, $arguments)

當我們調用不存在的方法時,__call() 會自動執行,用於進行異常處理,並使程式繼續正常運行

__call() 例子
class computer{    function start(){        echo "starting computer<br>";    }    function __call($m, $a){        echo "erro function: ".$m;        echo "<br>";        echo "error param: ";        print_r($a);        echo "<br>";    }}$myComputer = new computer();$myComputer->start();$myComputer->shutdown(‘10 min‘, ‘20 min‘);echo "here";

輸出結果為

starting computererro function: shutdownerror param: Array ( [0] => 10 min [1] => 20 min ) here

我們可以看到,$method 返回了錯誤的函數名,而 arguments 返回了參數,最後輸出了 "here" 說明程式繼續正常運行。

__clone() 方法 和 clone 關鍵字

clone 關鍵字用於複製對象,__clone() 方法實在複製對象時自動調用的函數

clone 例子
class computer{    public $name;    function __clone(){        echo "A computer has been cloned<br>";    }}$myComputer = new computer();$youComputer = $myComputer;$youComputer->name = ‘pc1‘;echo "My computer‘s name is ".$myComputer->name."<br>";echo "<br>";$hisComputer = clone $myComputer;$hisComputer->name = ‘pc2‘;echo "My computer‘s name is ".$myComputer->name."<br>";echo "His computer‘s name is ".$hisComputer->name."<br>";

輸出結果

My computer‘s name is pc1A computer has been clonedMy computer‘s name is pc1His computer‘s name is pc2

我們看到用 = 號並不能複製對象,只是為對象添加了一個別名而已,這裡 $myComputer 和 $youComputer 指向同一塊記憶體,修改了 $youComputer 的值相當於修改了 $myComputer 的值。

__autolaod()

在執行個體化對象時,__autolaod() 會自動被調用,用於快速取得對應的類檔案

__autoload() 例子
<?phpfunction __autoload($class_name) {    include $class_name . ‘.php‘;}$obj  = new MyClass1();$obj2 = new MyClass2(); ?>

摘自PHP手冊

帶 try, catch 異常處理的例子

function __autoload($class_name){    echo "want to load ".$class_name."<br>";    if(file_exists($class_name.".class.php")){        include($class_name.".class.php");    }else{        throw new Exception("Unable to laod ".$class_name.".class.php");    }}try{    $obj = new myClass();}catch(Exception $e){    echo $e->getMessage()."<br>";}

本文出自 “打個籃球就那麼難” 部落格,請務必保留此出處http://gipanda.blog.51cto.com/3808693/1423752

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.