zoukankan      html  css  js  c++  java
  • 接口实例化对象

    接口是实现多继承的。

    举个例子:

    鸟  和 猴子

    鸟可以飞,猴子可以爬树

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

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

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

     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
  • 相关阅读:
    m-n的随机整数 包括m n
    获取url参数 hash类型
    js 数组转带空格字符串
    产生n-m的随机数组
    js 判断android、IOS
    判断是否微信浏览器
    文本左右对齐方式css
    H5微信支付流程
    H5微信授权登录流程
    H5页面 input禁止弹出键盘
  • 原文地址:https://www.cnblogs.com/canbefree/p/3771171.html
Copyright © 2011-2022 走看看