PHP 5 正式版雖未發布,但開發版已展現革命性的物件導向改進。本文翻譯自 PHPBuilder.com 的 Luis Argerich 原著,重點介紹 PHP 5 三大核心新功能:新物件模型、結構化異常處理、命名空間。註:文中範例部分採用 PHP 4 寫法以利閱讀,最終特性以正式版為準。
PHP 5 的物件模型在 PHP 4 基礎上大幅升級,語法更接近 Java。以下逐一解析關鍵特性:
PHP 4 使用類名作為構造函數,且無析構函數。PHP 5 引入 __construct() 和 __destruct(),分別在物件建立與銷毀時自動調用:
<?php
class foo {
var $x;
function __construct($x) { $this->x = $x; }
function display() { print($this->x); }
function __destruct() { print("bye bye"); }
}
$o1 = new foo(4);
$o1->display(); // 輸出 4,結束時輸出 "bye bye"
?>
PHP 4 預設傳值,需用 & 傳址。PHP 5 物件永遠以引用方式指派:
<?php
class foo { var $x; function setX($x) { $this->x = $x; } function getX() { return $this->x; } }
$o1 = new foo; $o1->setX(4);
$o2 = $o1; $o1->setX(5);
if ($o1->getX() == $o2->getX()) print("Oh my god!"); // 輸出:兩物件同步變化
?>
__clone() 方法需獨立副本時,使用 clone 關鍵字觸發 __clone():
<?php
$o1 = new foo; $o1->setX(4);
$o2 = clone $o1; // PHP 5 建議用 clone 關鍵字
$o1->setX(5);
if ($o1->getX() != $o2->getX()) print("Copies are independant");
?>
PHP 5 引入三層存取控制,強化封裝性:
<?php
class foo {
private $x;
public function public_foo() { print("I'm public"); }
protected function protected_foo() { $this->private_foo(); print("I'm protected"); }
private function private_foo() { $this->x = 3; print("I'm private"); }
}
class foo2 extends foo {
public function display() {
$this->protected_foo(); // OK
$this->public_foo(); // OK
// $this->private_foo(); // 錯誤:無法存取父類別 private 方法
}
}
?>
PHP 不支援多重繼承,但 interface 允許類別實作多個介面:
<?php
interface displayable { function display(); }
interface printable { function doprint(); }
class foo implements displayable, printable {
function display() { /* 實作 */ }
function doprint() { /* 實作 */ }
}
?>
使用 abstract 關鍵字,可包含抽象方法(強制子類別實作)與具體方法:
<?php
abstract class foo {
protected $x;
abstract function display(); // 必須由子類別實作
function setX($x) { $this->x = $x; }
}
class foo2 extends foo {
function display() { /* 實作 */ }
}
?>
__call()、__set()、__get()__call($name, $arguments):呼叫不存在的方法時觸發,常用於實作方法多載__set($name, $value)、__get($name):存取未定義屬性時觸發<?php
// 方法多載範例
class Magic {
function __call($name, $arguments) {
if ($name == 'foo') {
if (is_int($arguments[0])) $this->foo_for_int($arguments[0]);
elseif (is_string($arguments[0])) $this->foo_for_string($arguments[0]);
}
}
private function foo_for_int($x) { print("oh an int!"); }
private function foo_for_string($x) { print("oh a string!"); }
}
$x = new Magic();
$x->foo(3); // 輸出 "oh an int!"
$x->foo("3"); // 輸出 "oh a string!"
?>
使用 static 關鍵字定義屬於類別而非實例的屬性與方法,透過 ClassName::$member 存取。
結語:PHP 5 的物件模型重寫奠定了現代 PHP 框架的基礎,掌握這些特性是進階開發的關鍵。建議搭配官方文件深入實作。