Why do I need to design abstract classes?
In actual development, there may be a class that is the parent of other classes, but it does not need to be instantiated in itself, and the primary purpose is to allow subclasses to inherit. This can achieve the purpose of code reuse, and also benefit project designers to design classes.
1. The format of the abstract class :
Abstract class class Name {
Abstract modifier function name (argument list);
}
<?php
Abstract class animal{
Public $name;
protected $age;
This method does not have a method body, mainly to allow subclasses to implement
Abstract public Function cry ();
}
Class Cat extends animal{
Public Function Cry () {
echo "The cat is barking!" ";
}
}
$cat 1=new Cat ();
$cat 1->cry ();
?>
2, with the abstract keyword to modify a class, this class is an abstract class, with the abstract keyword to modify a method, this method is an abstract method, the method can not have a method body.
3. Abstract classes cannot be instantiated
4. An abstract class does not necessarily include an abstract method, that is, an abstract class can have no abstract method.
5. Once the class contains the abstract method, the class must be declared abstract
6. Abstract methods cannot have function bodies
7, abstract class can have no abstract method, at the same time can have implemented the method
<?php
Abstract class animal{
Public $name = "www.bianceng.cn";
protected $age;
This method does not have a method body, mainly to allow subclasses to implement
Abstract public Function cry ();
Methods implemented in an abstract class
Public Function GetName () {
return $this->name;
}
}
Class Cat extends animal{
Public Function Cry () {
echo "The cat is barking!" ";
}
}
$cat 1=new Cat ();
$cat 1->cry ();
echo "<br/>". $cat 1->getname ();
?>
8. If a class inherits an abstract class, it must implement all the abstract methods of that abstract class, unless it itself is declared as an abstract class.
<?php
This is an abstract class
Abstract class a{
Abstract function test ();
}
Class B extends a{
function test () {//This method will complain if it is not implemented
echo "www.bianceng.cn";
}
}
echo "Good";
?>
Url:http://www.bianceng.cn/webkf/php/201612/50479.htm