執行個體簡介PHP的一些進階物件導向編程的特性_php技巧

來源:互聯網
上載者:User

一般來說,學習PHP需要瞭解下面的一些特性:

對象複製。PHP5中對OOP模型的主要改進之一,是將所有對象都看作引用,而不是值。但是,如果所有對象都視為引用,那麼如何建立對象的副本呢?答案是通過複製對象。

<?phpclass 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());?>

繼承。如前面所述,通過繼承來構建類層次體系是OOP的關鍵概念。

class Employee { ...}class Executive extends Employee{ ...}class CEO extends Executive{ ...}

介面。介面是一些未實現的方法定義和常量的集合,相當於一種類藍本。介面只定義了類能做什麼,而不涉及實現的細節。本章介紹PHP5對介面的支援,並提供了一些展示這個強大OOP特性的例子。

<?phpinterface 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}

命名空間。命名空間可根據上下文劃分各種庫和類,幫肋你更為有效地管理程式碼程式庫。

<?phpnamespace Library;class Clean { function printClean() { echo "Clean..."; }}?><?phpinclude "test.php";$clean = new \Library\Clean();$clean->printClean();?>

如果你使用過其他物件導向語言,可能會感到奇怪,為什麼上述特性沒有包括其他語言中熟悉的一些OOP特性?原因很簡單,PHP不支援這些特性。為了讓你不再感到迷惑,下面列出PHP不支援的進階OOP特性。

  • 方法重載。PHP不支援通過函數重載實現多態,根據Zend網站的討論,可能永遠都不會支援。要瞭解具體原因,可以查看http://www.zend.com/php/ask_experts.php
  • 操作符重載。目前不支援根據所修改資料的類型為操作符賦予新的含義。根據zend網站的討論,將來實現這個特性的可能性也不大。
  • 多重繼承。PHP不支援多重繼承。但是支援實現多個介面。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.