zoukankan      html  css  js  c++  java
  • php的抽象类

    php的抽象类


    //定义一个老虎类
    abstract class Tiger{
        public abstract function climb();    
    }
    
    //定义一个孟加拉虎类
    class MTiger extends Tiger{
        public function climb(){
            echo '孟加拉虎,会爬树';
        }
    }
    
    //定义一个西伯利亚虎类
    class XTiger extends Tiger{
        public function climb(){
            echo '西伯利亚虎,不会爬树';
        }
    }
    
    //定义一个猫类
    class Cat{
        public function climb(){
            echo '猫,会爬树';
        }
    }
    
    //定义一个动物类
    class Client{
        static function call(XTiger $animal){
            $animal->climb();
        }
    
        static function call2(Tiger $animal){
            $animal->climb();
        }
    
        static function call3($animal){
            $animal->climb();
        }
    }
    
    Client::call(new XTiger());//正确
    
    Client::call(new MTiger());//不正确
    //Fatal error: 
    //Uncaught TypeError: Argument 1 passed to Client::call() must be an instance of XTiger, instance of MTiger given, called in ...
    Client::call(new Cat());//不正确
    //Uncaught TypeError: Argument 1 passed to Client::call() must be an instance of XTiger, instance of MTiger given, called in ...
    
    echo '<hr>';
    Client::call2(new XTiger());//正确
    Client::call2(new MTiger());//正确
    
    Client::call2(new Cat());//不正确
    //Fatal error: Uncaught TypeError: Argument 1 passed to Client::call2() must be an instance of Tiger, instance of Cat given, called in
    
    echo '<hr>';
    
    Client::call3(new XTiger());//正确
    Client::call3(new MTiger());//正确
    Client::call3(new Cat());//正确

    总结:

    1、定义为抽象的类不能被实例化;
    2、如果一个类里面至少有一个方法是被声明为抽象的,
    那么这个类就必须被声明为抽象的。
    3、被定义为抽象的方法只是声明了其调用方式(参数),不能定义其具体的
    功能实现。
    4、继承一个抽象类的时候,子类必须定义父类中的所有抽象方法,
    这些方法的访问控制必须和父类中一样(或者更为宽松)

    5、当参数指定类型时,必须符合类型,示例中:

       Client类的call方法,参数指定为 XTiger 时,只能传递Xtiger对象;

      Client类的call2方法,参数指定为 Tiger 时,只能传递Tiger的子类的对象;

      Client类的call3方法,参数不指定类型时,可以传递任何参数。

    6、抽象类的关键字,abstract。


  • 相关阅读:
    结对项目开始
    团队项目开始
    个人项目总结
    python面向对象
    OSI七层模型
    Django中的orm的惰性机制
    Python装饰器
    python运算符
    python元祖和列表
    Sencha Touch 1.x 快速入门 第三章 布局(2) Card布局
  • 原文地址:https://www.cnblogs.com/gyfluck/p/9674400.html
Copyright © 2011-2022 走看看