PHP中__construct(), __destory(), __get(), __set(), __call(),_PHP教程

來源:互聯網
上載者:User
(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!”

http://www.bkjia.com/PHPjc/478729.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/478729.htmlTechArticle(1)__construct() 是PHP內建的建構函式, 是同PHP 解析引擎自動調用的, 當執行個體化一個對象的時候,這個對象的這個方法首先被調用。 例:c...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.