Heim  >  Artikel  >  Backend-Entwicklung  >  实例简介PHP的一些高级面相对象编程的特性_PHP

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

WBOY
WBOYOriginal
2016-05-29 11:47:39998Durchsuche

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

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

<&#63;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 <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());
&#63;>

继承。如前面所述,通过继承来构建类层次体系是OOP的关键概念。

class Employee {
 ...
}

class Executive extends Employee{
 ...
}

class CEO extends Executive{
 ...
}

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

<&#63;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);
&#63;>

抽象类。抽象类实质上就是无法实例化的类。抽象类将由可实例化的类继承,后者称为具体类(concreate class)。抽象类可以完全实现、部分实现或者根本未实现。

abstract class Class_name
{
 //insert attribute definitions here
 //insert method definitions here
}

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

<&#63;php
namespace Library;
class Clean {
 function printClean() {
 echo "Clean...";
 }
}
&#63;>

<&#63;php
include "test.php";
$clean = new \Library\Clean();
$clean->printClean();
&#63;>

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

  • 方法重载。PHP不支持通过函数重载实现多态,根据Zend网站的讨论,可能永远都不会支持。要了解具体原因,可以查看http://www.zend.com/php/ask_experts.php
  • 操作符重载。目前不支持根据所修改数据的类型为操作符赋予新的含义。根据zend网站的讨论,将来实现这个特性的可能性也不大。
  • 多重继承。PHP不支持多重继承。但是支持实现多个接口。
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn