1. Abstract class
An abstract class cannot be instantiated directly, it must inherit the abstract class first, and then instantiate the subclass. At least one abstract method should be included in the abstract class. If a class method is declared abstract, it cannot include the implementation of a specific feature. When inheriting an abstract class, the subclass must contain all the abstract methods in the abstract class, and the methods must be the same or looser as the methods in the abstract class, such as the abstract method in the abstract class is protected, then the methods in the subclass must be protected or public. cannot be private. For example:
//Defining abstract ClassesAbstract classabstractclass{//defines the methods that must be included in the subclass, and is more relaxed Abstract protected functionGetValue (); Abstract protected functionPrefixvalue ($prefix); //Common Methods Public functionPrintOut () {return $this-GetValue (); }}//subclass inherits Abstract classclassConcreteClass1extendsabstractclass{protected functionGetValue () {return"ConcreteClass1"; } Public functionPrefixvalue ($prefix){ return $prefix." ConcreteClass1 "; }}classConcreteClass2extendsabstractclass{ Public functionGetValue () {return"ConcreteClass2"; } Public functionPrefixvalue ($prefix){ return $prefix." ConcreteClass2 "; } Public functionAA () {return"AA"; }}$class 1=NewConcreteClass1 ();Echo $class 1->printout (). ' <br/> ';Echo $class 1->prefixvalue (' Foo '). ' <br/> ';$class 2=NewConcreteClass2 ();Echo $class 2->printout (). ' <br/> ';Echo $class 2->getvalue (). ' <br/> ';Echo $class 2->prefixvalue (' Bar '). ' <br/> ';Echo $class 2->aa ();
2. Interface (interface)
Using interfaces (interface), you can specify which methods a class must implement, but you do not need to define the specifics of these methods.
We can define an interface through interface, just like defining a standard class, but all of the methods defined in it are empty.
All methods defined in the interface must be public, which is the attribute of the interface.
Interfaces are implemented using implements
Interfaceitemplate{ Public functionsetvariable (); Public functiongethtml (); }classTemplateImplementsitemplate{ Public functionsetvariable () {return' GetVariable '; } Public functiongethtml () {return"Gethtml"; } Public functionAA () {return' AA '; }}$template=NewTemplate ();Echo $template-setvariable ();Echo $template-gethtml ();Echo $template->aa ();
3. The difference between interface (interface) and abstract class
Abstract classes can have attributes, abstract methods, and common methods, and interfaces can have no common methods and properties, only constants and abstract methods (no method body);
The grammatical difference
PHP Abstract Classes and interfaces