Detailed explanation of PHP interface

【Foreword】

     This article summarizes the knowledge points related to the PHP interface

 

【main body】

(1) The concept of interface

 An abstract class can be understood as a "class template", and an interface is a "method template".

Interfaces are more granular and are used to describe common methods.

<?php
    interface fly1{
        public function fly($oil,$height);
    }
    interface run1{
        public function run($speed,$width);
    }
    interface water1{
        public function water($depth);
    }
    //declare a class that implements its interface
    class Super implements fly1,run1,water1{
        //Same as abstract classes and abstract methods, for the interfaces in the declared class, each interface must be implemented one by one,
      // not one less
        public function fly($oil,$height){
            echo "fly";
        }
        public function run($speed,$width){
            echo "跑";
        }
        public function water($depth){
            echo "swimming";
        }
    }
    $super = new Super();
    $super -> fly(1,2);//Because the above interface stipulates that parameters must be passed in, so it must be passed in regardless of whether it is used or not, otherwise an error will be reported
?>

 

 

(2) Syntax of the interface

①The interface itself is abstract, and there is no need to add abstract before the method;

② The methods in the interface can only be public;

③ A class can implement multiple interfaces at the same time. For example, fly1, run1, water1 in the following example

//declare a class that implements its interface
    class Super implements fly1,run1,water1{
        //Same as abstract classes and abstract methods, for the interfaces in the declared class, each interface must be implemented one by one
       // not one less
        public function fly($oil,$height){
            echo "fly";
        }
        public function run($speed,$width){
            echo "跑";
        }
        public function water($depth){
            echo "swimming";
        }
    }

 

【Summarize】

      An abstract class is equivalent to a specification of a class of things; an interface: a specification of the parts that make up a thing

 

 

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326117240&siteId=291194637