PHP中__construct(), __destory(), __get(), __set(), __call(), __toString(), __clone()

(1)__construct() 是PHP內置的構造函數, 是同PHP 解析引擎自動調用的, 當實例化一個對象的時候,這個對象的這個方法首先被調用。

例:class Test

       {

             function __construct()

            {

                  echo "This is __construct function!";

             }

            function Test()

           {

                  echo "This is Test!";

           }

     }

$objTest = new Test;      // 運行結果是“This is __construct function!”


(2)__destory()是PHP內置的析構函數,當刪除一個對象或對象操作終止的時候,調用該方法,所以可進行釋放資源之類的操作。

class Test

{

      function __destory()

      {

            echo "This is __destory function!";

       }

}

$objTest = new Test;       // 運行結果是“This is __destory function!”


(3)__get()當試圖讀取一個並不存在的屬性的時候被調用,類似java中反射的各種操作。

class Test

{

      function __get($key)

     {

           echo $key, "doesn't exist!";

      }

}

$objTest = new Test;

$objTest->Name;    // 運行結果是“Name does'nt exist!”


(4)__set()當試圖向一個並不存在的屬性寫入值的時候被調用。

class Test

{

      function __set($key, $val)

       {

              echo “Can't assign\"” . $val . "\" to ". $key;

      }

}

$objTest = new Test;

$objTest->Name = "ljlwill";    // 運行結果是“Can't assign "ljlwill" to Name”


(5)__call()當試圖調用一個對象並不存在的方法時,調用該方法。

class Test

{

     function __call($key, $args)

    {

          echo "The function \"". $key ."\" doesn't exist. it's args are ". print_r($args);

    }

}

$objTest = new Test;

$objTest->getName("2004", "ljlwill");

// 運行結果是 The function "getName" doesn't exist. it's args are: Array(

   [0] => 2004;

   [1] => ljlwill;

)


(6)__toString() 當打印一個對象的時候被調用,類似於java的toString方法,當我們直接打印對象的時候回調用這個函數。

class Test

{

     function __toString()

     {

              return "This is Test!";

     }

}

$objTest = new Test;

eho $objTest;         // 運行結果是“This is Test!”


(7)__clone() 當對象被克隆時,被調用。

class Test

{

        function __clone()

         {

                echo "I am cloned!" ;
         }

}

$objTest = new Test;

$objCloneTest = clone $objTest;     // 運行結果是“I am cloned!”

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章