本篇接續上篇PHP-物件導向(OOP)介紹-Part1
PHP
提供了數個魔術函數讓操作物件(Object)變得更簡單,魔術函數會在物件發生特定行為
時被呼叫,
這讓開發者更容易達成某些有用的任務,以下帶大家看幾個例子。
當一個物件被建立時,它經常需要做一些初始化,construct():是當一個物件被建立的時候會被呼叫
。
以下為增加一個construct()到 MyClass
,讓MyClass
被實例化的時候丟出一段訊息
<?php
class MyClass
{
public $prop1 = "I'm a class property!";
public function __construct() //物件被建立時呼叫訊息
{
echo 'The class "' . __CLASS__ . '" was initiated!<br />';
}
public function setProperty($newval)
{
$this->prop1 = $newval;
}
public function getProperty()
{
return $this->prop1 . "<br />";
}
}
$obj = new MyClass; //建立新物件。
echo $obj->getProperty(); //呼叫物件到`getProperty()`。
echo "End of file.<br />"; //結束時丟出訊息`End of file.`。
輸出到畫面會顯示
The class "MyClass" was initiated!
I'm a class property!
End of file.
而當物件被摧毀的時候,destruct():當一個物件被摧毀的時候會被呼叫
。
增加一個destruct()到MyClass
,讓MyClass
被摧毀時的時候,丟出一段訊息
<?php
class MyClass
{
public $prop1 = "I'm a class property!";
public function __construct() //物件被建立時呼叫訊息
{
echo 'The class "', __CLASS__, '" was initiated!<br />';
}
public function __destruct() //物件被結束時呼叫訊息
{
echo 'The class "', __CLASS__, '" was destroyed.<br />';
}
public function setProperty($newval)
{
$this->prop1 = $newval;
}
public function getProperty()
{
return $this->prop1 . "<br />";
}
}
$obj = new MyClass; //建立新物件。
echo $obj->getProperty(); //呼叫物件到`getProperty()`。
echo "End of file.<br />"; //結束時丟出訊息`End of file.`。
輸出到畫面會顯示
The class "MyClass" was initiated!
I'm a class property!
End of file.
The class "MyClass" was destroyed.
toString()
:避免程式試圖將MyClass
當作字串輸出到瀏覽器上(被當作字串處理時觸發),
如果把物件當作字串處理的話,在PHP
中會出現無法轉換型態的錯誤
<?php
class MyClass
{
public $prop1 = "I'm a class property!";
public function __construct() //物件被建立時呼叫訊息。
{
echo 'The class "', __CLASS__, '" was initiated!<br />';
}
public function __destruct() //物件被結束時呼叫訊息。
{
echo 'The class "', __CLASS__, '" was destroyed.<br />';
}
public function __toString() //將物件轉換為字串。
{
echo "Using the toString method: ";
return $this->getProperty();
}
public function setProperty($newval)
{
$this->prop1 = $newval;
}
public function getProperty()
{
return $this->prop1 . "<br />";
}
}
$obj = new MyClass; //建立新物件。
echo $obj; //呼叫已被轉為字串的物件。
echo "End of file.<br />"; //結束時丟出訊息`End of file.`。
輸出到畫面會顯示
The class "MyClass" was initiated!
Using the toString method: I'm a class property!
End of file.
The class "MyClass" was destroyed.
當然除了本篇提到的三個魔術函數以外,還有更多魔數函數可以在PHP : Magic Methods可以學習,
本篇介紹到此,下次見~