• 接口实例化对象


    接口是实现多继承的。

    举个例子:

    鸟  和 猴子

    鸟可以飞,猴子可以爬树

    还有个对象叫孙悟空  他能飞,也能爬树

    这中情况就用接口来实现。

    接口实例化对象类似于函数指针。

     1 <?php
     2 // require_once './meus.php';
     3 
     4 // 接口对象的实例化
     5 interface Person
     6 {
     7 
     8     public function name();
     9 }
    10 
    11 class My implements Person
    12 {
    13 
    14     public function name()
    15     {
    16         echo "myname is x";
    17     }
    18 }
    19 
    20 class You implements Person
    21 {
    22 
    23     public function name()
    24     {
    25         echo "myname is y";
    26     }
    27 }
    28 
    29 class Who
    30 {
    31 
    32     private $per;
    33 
    34     public function __construct(Person $per)
    35     {
    36         $this->per = $per;
    37     }
    38     
    39     public function sname(){
    40         return $this->per->name();
    41     }
    42     
    43 }
    44 
    45 $per=new my();
    46 $w=new Who($per);
    47 
    48 echo $w->sname();
    Interface
     1 <?php
     2 // 接口对象的实例化
     3 header ( "Content-Type:text/html;charset=utf-8" );
     4 interface monkey {
     5     function climb();
     6 }
     7 interface bird {
     8     function fly();
     9 }
    10 
    11 
    12 class Person implements monkey {
    13     function climb() {
    14         echo "我是一个人类,我也可以像猴子一样爬树哦";
    15     }
    16 }
    17 
    18 class Plane implements bird {
    19     function fly(){
    20         echo "飞机也能像鸟儿一样飞";
    21     }
    22 }
    23 
    24 class Sunhouzi implements monkey, bird {
    25     public function climb() {
    26         echo "我能爬树!";
    27     }
    28     public function fly() {
    29         echo "我能飞哦!";
    30     }
    31 }
    32 
    33 class Who{
    34     private $interface;
    35     public function __construct(monkey $interface){
    36         $this->interface=$interface;
    37     }
    38     
    39     public function climb(){
    40         $this->interface->climb();
    41     }
    42 }
    43 
    44 
    45 $s=new Who(new Person());
    46 $s->climb();
    View Code
  • 相关阅读:
    几个计算广告学的课程
    Jie Bao 牛人cv
    如果英剧《黑镜子》拍第三季,你来写一集剧本策划,你想写一个什么样的故事呢? 知乎
    设计模式之迭代器与组合模式
    javascript 时钟clock
    项目中的需求蔓延
    一个产生随机random markers 例子
    设计模式之模板方法模式
    设计模式之反(向)模式
    转:用函数式编程技术编写优美的 JavaScript
  • 原文地址:https://www.cnblogs.com/canbefree/p/3771171.html
Copyright © 2020-2023  润新知