PHP高级面向对象编程特性概述
通常而言,掌握PHP需关注以下核心特性:
对象克隆是PHP5对面向对象模型的重要改进,它将所有对象视为引用而非值。若所有对象均为引用,则需通过克隆操作来创建对象的副本。
<?php
class Corporate_Drone{
private $employeeid;
private $tiecolor;
function setEmployeeID($employeeid) {
$this->employeeid = $employeeid;
}
function getEmployeeID() {
return $this->employeeid;
}
function setTiecolor($tiecolor) {
$this->tiecolor = $tiecolor;
}
function getTiecolor() {
return $this->tiecolor;
}
}
$drone1 = new Corporate_Drone();
$drone1->setEmployeeID("12345");
$drone1->setTiecolor("red");
$drone2 = clone $drone1;
$drone2->setEmployeeID("67890");
printf("drone1 employeeID:%d
",$drone1->getEmployeeID());
printf("drone1 tie color:%s
",$drone1->getTiecolor());
printf("drone2 employeeID:%d
",$drone2->getEmployeeID());
printf("drone2 tie color:%s
",$drone2->getTiecolor());
?>
继承是构建类层次体系的关键概念,如前文所述,这是面向对象编程的基础。
class Employee {
...
}
class Executive extends Employee{
...
}
class CEO extends Executive{
...
}
接口由未实现的方法定义和常量集合构成,充当类的蓝图。它仅规定类具备的功能,不涉及具体实现细节。本节阐述PHP5对接口的支持,并提供展示这一强大特性的示例。
<?php
interface IPillage
{
// CONST 1;
function emptyBankAccount();
function burnDocuments();
}
class Employee {
}
class Excutive extends Employee implements IPillage {
private $totalStockOptions;
function emptyBankAccount() {
echo "Call CFO and ask to transfer funds to Swiss bank account";
}
function burnDocuments() {
echo "Torch the office suite.";
}
}
class test {
function testIP(IPillage $ib) {
echo $ib->emptyBankAccount();
}
}
$excutive = new Excutive();
$test = new test();
echo $test->testIP($excutive);
?>
抽象类即无法被实例化的类,将由可实例化的具体类(concreate class)继承。抽象类可实现全部功能、部分实现或未实现任何功能。
abstract class Class_name
{
//insert attribute definitions here
//insert method definitions here
}
命名空间允许根据上下文对各类库和类进行划分,从而更有效地管理代码库。
<?php
namespace Library;
class Clean {
function printClean() {
echo "Clean...";
}
}
?>
<?php
include "test.php";
$clean = new \Library\Clean();
$clean->printClean();
?>
若熟悉其他面向对象语言,可能会疑惑为何上述特性未包含那些语言中的常见OOP特性。原因在于PHP并不支持这些特性。为消除困惑,下文列出PHP不支持的高级OOP特性。
- 方法重载:PHP不支持通过函数重载实现多态,据Zend网站讨论,未来可能永远不支持。具体原因可参阅http://www.zend.com/php/ask_experts.php。
- 操作符重载:目前不支持根据修改数据的类型为操作符赋予新含义。据Zend网站讨论,将来实现该特性的可能性也较小。
- 多重继承:PHP不支持多重继承,但支持实现多个接口。