PHP物件導向學習之二:深入理解物件導向進階特性

來源:互聯網
上載者:User
PHP物件導向學習之二:深入瞭解物件導向進階特性

靜態方法(static)和屬性:通過類而不是對象來訪問資料和功能

靜態方法是以類作為作用於的函數,不能訪問這個類中的普通屬性,因為那些屬性屬於一個對象,但可以訪問靜態屬性。

如果修改了一個靜態屬性,那麼這個類的所有執行個體都能訪問到這個新值。

例如:

print staticExample::$aNum;StaticExample::sayHello();

要點:除非是訪問一個被覆寫的方法,負責永遠只能用::訪問被明確聲明為static的方法和屬性。

①:不能在對象中調用靜態方法

②:不能在靜態方法中使用偽變數$this

id=$id; } public static function getInstance($id, PDO $pdo){ $stmt=$pdo->prepare("select * from products where id=?"); $result=$stmt->execute(array($id)); $row=$stmt->fetch(); //執行個體化CD類 $product=new CDProudct($row['title'], $row['firstname'], $row['mainname'], $row['price'], $row['playlength']); $product->setId($row['id']); $product->setDiscount($row['dusciybt']); return $product; } } /*  * 這樣的方法有點像 工廠,可以接受未經處理資料或配置 據此產生對象  */ $dsn='sqlite://home/db/bob/projects/products.db'; $pdo=new PDO($dsn, null, null); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $obj=shopProduct::getInstance(1, $pdo); 

抽象類別(abstract class)和介面(interface):設計和現實相分離

抽象類別不能直接被執行個體化,只定義(活部分實現)子類需要的方法,子類可以繼承它並且通過實現其中的抽象方法,使抽象類別具體化。

抽象類別至少包含一個抽象方法

abstract class shopProductWriter{    protected $products=array();    abstract public function write();}

products[]=$shopProduct;}abstract public function write();}/** * 輸出XML */class xmlProductWriter extends shopProductWriter{public function write(){$str=''."\n";$str.="\n";foreach ($this->products as $shopProduct){$str.="\tgetTitle()."\">\n";//...}$str.="\n";}}


抽象類別提供了具體實現的標準,而介面(interface)則是純粹的模板。介面只能定義功能,而不包含實現的內容

介面可以包含屬性和方法聲明,但是方法為空白

例如:

interface Chargeable{  public function getPrice();}

class shopProduct implements Chargeable{  //...  public function getPrice(){    return ;//...  }}

攔截器方法:自動委託

PHP提供內建攔截器interceptor方法,可以 攔截 發送到未定義發放和屬性的訊息。

__get($property) 訪問未定義的屬性時被調用

__set($property,$value) 給未定義的屬性賦值時被調用

__isset($property) 對未定義的屬性調用isset()時被調用

__unset($property) 對未定義的屬性調用unset()時被調用

__call($method,$arg_array) 調用未定義的方法時被調用

$method();}}function getName(){return "Bob";}function getAge(){return 24;}}$p= new Person();print $p->name;

析構方法:對象銷毀前的清理工作

在對象被垃圾收集器收集前(即對象從記憶體中刪除之前)自動調用。

name=$name;$this->age=$age;}function setID($id){$this->id=$id;}function __destruct(){if(!empty($this->id)){//儲存Person資料 print "saving person\n";}}}$person=new Person("bob", 24);$person->setID(111);unset($person);//輸出//儲存Person

回調:用匿名函數為組件添加功能


  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.