• [轉]对PHP接口的理解


    From : http://www.cnvar.net/198711.html

     

    以前学JAVA的时候就对接口理解过一回,最近在看PHP的OOP特性,发现和JAVA很像,就是语法上有不同,但是有关资料少的可怜,找到了几个也不能充分说明PHP下接口的特性,自己又看了一遍孙鑫老师的JAVA视频教程,有关接口的部分,昨天总算是理解了。真的感觉是豁然开朗。把自己写的PHP接口部分的示例程序发上来。

    VideoCard.php 接口文件(显卡的功能接口定义)

    <?php 
    interface VideoCardInter{
    function Display();
    function getName();
    }
    ?>


    Dmeng.php 实现接口(帝盟的厂家实现了这些接口,怎么实现的,主板厂家不用管)

    <?php 
    include_once("VideoCard.php");
    class Dmeng implements VideoCardInter {
    function Display(){
    echo "Display";
    }
    function getName(){
    return "Dmeng VideoCard";
    }
    }
    ?>




    Mainboard.php  应用接口(把显卡插到主板上,主板只要用这些接口就行了,也可以不用)

    <?php 
    include_once("VideoCard.php");
    include_once("Dmeng.php");
    class Mainboard{
    var $vc;
    function run(VideoCardInter $vc){ //定义VideoCardInter接口类型参数,这时并不知道是谁来实现。
    $this->vc=$vc;
    $this->vc->Display();
    echo "主板运行!";
    }
    }

    $conputer=new Mainboard(); //实例化一台新计算机
    $conputer->run(new Dmeng); //用的时候把实现接口类的名称写进来,(现在是帝盟的显卡,也可以换成别的场家的,只要他们都实现了接口)
    ?>


    由于PHP是动态语言,所以类型不能像JAVA一样定的很死,定义接口的时候,写上返回类型反而出错,估计PHP6的时候可能写义的要严格一些吧。
    PS:我只把最基本的部分写上,还可以加CPU等接口。

    下面是自己寫的三層結構測試代碼

    <?php
    $GLOBALS['WebConfig']['DAO'] = "MySql";

    interface IProduct{
    function Display();
    function getName();
    }
    class SqlProductDao implements IProduct {
    function Display(){
    echo "Sql Display";
    }
    function getName(){
    return "Sql Dmeng VideoCard";
    }
    }

    class MySqlProductDao implements IProduct {
    function Display(){
    echo "MySql Display";
    }
    function getName(){
    return "MySql Dmeng VideoCard";
    }
    }

    class DAOFactory{
    public static function getDAO($ClassName){
    $class = new ReflectionClass($GLOBALS['WebConfig']['DAO'].$ClassName);
    $instance = $class->newInstance();
    return $instance;
    }
    }

    class ProductBLL{
    private $iproduct;
    function __construct(IProduct $iproduct){
    $this->iproduct=$iproduct;
    }
    function Display(){
    $this->iproduct->Display();
    }
    function getName(){
    return $this->iproduct->getName();
    }
    }

    $productbill = new ProductBLL(DAOFactory::getDAO("ProductDao"));
    $productbill->Display();
    //echo($productbill->getName());
    ?>



  • 相关阅读:
    神通数据库 SQL 异常捕获
    StringBuilder Append 和 AppendLine 的细节
    Linux (Debian) 安装 Sqlplus 工具
    linux杀掉所有相关进程进程
    java和python 重写和重载
    python 深复制和浅复制
    python 闭包
    os.makedirs 权限问题
    python多进程和多线程
    python工厂函数
  • 原文地址:https://www.cnblogs.com/Athrun/p/2242373.html
Copyright © 2020-2023  润新知