This article analyses the difference and choice of abstract class and interface in PHP. Share to everyone for your reference, specific as follows:
Difference:
1, the use of the interface is through the keyword implements. The use of abstract classes is extends by keyword. Of course, interfaces can also be inherited by keyword extends.
2. You cannot declare member variables (including class static variables) in an interface, but you can declare class constants. You can declare various types of member variables in an abstract class to implement the encapsulation of the data. (The member variables in the other Java interface are declared as public static final types)
<?php
abstract class Father {
function meth1 () {
echo "meth1...<br>";
}
Abstract function meth2 ();
Public $var 1= "var1";
public static $var 2= "Var2";
Const var3= "VAR3";
}
Class Son extends Father {
function meth2 () {
echo "meth2 of son...<br>";
}
}
$s =new Son ();
Echo $s->var1. " <br> ";
echo Father:: $var 2. " <br> ";
echo Father::var3. " <br> ";
Interface ifather {
//public $iVar 1= "IVAR1"; the interface definition cannot contain member variables
//public static $iVar 2= "IVar2"; The interface definition here cannot contain static variables
const ivar3= "IVAR3";
function iMeth1 ();
}
Class Ison implements Ifather {
function iMeth1 () {
echo "imeth1...<br>";
}
}
$is =new Ison ();
echo ifather::ivar3;
? >
3, the interface does not have constructors, abstract classes can have constructors.
4, the methods in the interface are public types by default, and methods in the abstract class can be decorated with private,protected,public.
5. A class can implement multiple interfaces at the same time, but a class can only inherit from an abstract class.
Abstract class or interface
1. If you want to create a model, this model will be adopted by some tightly related objects, and you can use abstract classes. If you want to create a feature that will be taken by some unrelated objects, use an interface.
2. Use an interface if you must inherit behavior from multiple sources.
3. If you know that all classes share a common behavior implementation, use an abstract class and implement that behavior in it.
More interested in PHP related content readers can view the site topics: "PHP Network Programming Skills Summary", "PHP basic Grammar Introductory Course", "PHP operation Office Document Skills Summary (including word,excel,access,ppt)", " PHP Date and Time usage summary, PHP Introduction to object-oriented Programming, PHP String (String) Usage summary, PHP+MYSQL database Operations Tutorial and PHP Common database operating Skills summary
I hope this article will help you with the PHP program design.