实例简介PHP的一些高级面向对象编程的特性

(编辑:jimmy 日期: 2024/9/30 浏览:2)

一般来说,学习PHP需要了解下面的一些特性:

对象克隆。PHP5中对OOP模型的主要改进之一,是将所有对象都看作引用,而不是值。但是,如果所有对象都视为引用,那么如何创建对象的副本呢?答案是通过克隆对象。

<"12345");
$drone1->setTiecolor("red");
$drone2 = clone $drone1;
$drone2->setEmployeeID("67890");

printf("drone1 employeeID:%d <br />",$drone1->getEmployeeID());
printf("drone1 tie color:%s <br />",$drone1->getTiecolor());
printf("drone2 employeeID:%d <br />",$drone2->getEmployeeID());
printf("drone2 tie color:%s <br />",$drone2->getTiecolor());
"htmlcode">
class Employee {
 ...
}

class Executive extends Employee{
 ...
}

class CEO extends Executive{
 ...
}

接口。接口是一些未实现的方法定义和常量的集合,相当于一种类蓝本。接口只定义了类能做什么,而不涉及实现的细节。本章介绍PHP5对接口的支持,并提供了一些展示这个强大OOP特性的例子。

<"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);
"htmlcode">
abstract class Class_name
{
 //insert attribute definitions here
 //insert method definitions here
}

命名空间。命名空间可根据上下文划分各种库和类,帮肋你更为有效地管理代码库。

<"Clean...";
 }
}
"test.php";
$clean = new \Library\Clean();
$clean->printClean();
?>

如果你使用过其他面向对象语言,可能会感到奇怪,为什么上述特性没有包括其他语言中熟悉的一些OOP特性?原因很简单,PHP不支持这些特性。为了让你不再感到迷惑,下面列出PHP不支持的高级OOP特性。

  • 方法重载。PHP不支持通过函数重载实现多态,根据Zend网站的讨论,可能永远都不会支持。要了解具体原因,可以查看http://www.zend.com/php/ask_experts.php
  • 操作符重载。目前不支持根据所修改数据的类型为操作符赋予新的含义。根据zend网站的讨论,将来实现这个特性的可能性也不大。
  • 多重继承。PHP不支持多重继承。但是支持实现多个接口。