php設計模式之接口

認真閱讀:OPP和設計模式的另一個組成是接口(interface),接口也有抽象方法,不過不像在抽象類中那樣包含具體方法和變量(但是可以包含具體常量——php獨有特性),關於接口是設計模式和OOP重要結構要素;

 

要創建一個接口要使用關鍵字interface而不是class、一般約定接口以I或者i開頭;下面舉個簡單的例子:IMethodHoder.php

<?php
interface IMethodHoder{

    public function getInfo();

    public function sendInfo($info);

    public function calculate($first,$sencond);
}

要實現一個接口,需要使用implements語句而不是extend,實例:ImplementAlpha.php

<?php
//引入IMethodHoder接口文件
include_once('IMethodHoder.php');

class ImplementAlpha implements IMethodHoder{
    public function getInfo($info)
    {
        // TODO: Implement getInfo() method.
        echo "This is NEWS! ".$info."<br/>";
    }

    public function sendInfo($info)
    {
        // TODO: Implement sendInfo() method.
        return $info;
    }

    public function calculate($first, $sencond)
    {
        // TODO: Implement calculate() method.
        $calculated = $first * $sencond;
        return $calculated;
    }
    public function useMethods()
    {
        $this->getInfo('The Sky is Blue……');
        echo $this->sendInfo('She is a girl!')."<br/>";
        echo "You make $". $this->calculate(5,30) . " In your part-time job!<br/>";
    }
}

$woker = new ImplementAlpha();
$woker->useMethods();

需要說明。除了實現接口中的方法外,ImplementAlpha類中還包含了useMethods(),只要保證實現了接口中的所有方法,就可以根據需要增加更多的其他方法和屬性

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章