In this article we introduce what abstract classes are and an introduction to their usage.
What is an abstract class?
Abstract classes cannot be instantiated, and the same methods are not implemented. Only method declarations are provided without specific implementation. Abstract classes can only be used as parent classes of other classes. Abstract classes are declared using the abstract keyword, and the syntax format is:
abstract class AbstractName{ ..... }
Note:
Abstract classes are similar to ordinary classes, both have member variables and member methods. But there is a difference. A class containing an abstract method must itself be abstract. An abstract method has no method body, and its functions can only be completed in subclasses. Abstract methods are also modified using the abstract keyword, in the format:
abstract function abstractName();
The abstract method is followed by a semicolon instead of curly braces "{}".
What is the role of abstract classes?
Among our classes, many classes will be written repeatedly. At this time, we can use the concept of abstract classes to write a public class, and we can call it repeatedly after instantiation. An abstract class is like a large warehouse with many things in it. You are not required to use everything in the warehouse. You can call it when you need it. If you feel dissatisfied with the items in the warehouse, you can also create a new one yourself.
Abstract methods and abstract classes are mainly used in complex class hierarchies. This hierarchical relationship needs to ensure that each subclass contains and overloads certain specific methods. This can also be achieved through interfaces.
Explanation of abstract class examples:
<?php header("content-type:text/html;charset=utf-8"); abstract class Member{ abstract function vipMember($name,$level,$money); } class Member1 extends Member{ function vipMember($name,$level,$money){ echo "您在PHP中文网的会员名是:" . $name; echo '<br/>'; echo "您的会员等级是:" . $level; echo '<br/>'; echo "您发文章赚取的钱是:" . $money; } } class Member2 extends Member{ function vipMember($name,$level,$money){ echo "您在PHP中文网的会员名是:" . $name; echo '<br/>'; echo "您的会员等级是:" . $level; echo '<br/>'; echo "您要提取" . $money . "元"; } } $member1 = new Member1(); $member2 = new Member2(); $member1->vipMember('大白','三级','24.35'); echo '<br/>'; echo '<hr/>'; $member2->vipMember('小明','五级','84.73');
First create a member abstract class, which contains an abstract method vipMember. Generate two subclasses, Member1 and Member2, for the abstract class, and implement abstract methods in the two subclasses respectively. Finally, instantiate two objects, call the implemented abstract method, and finally output.
The above is the detailed content of What is an abstract class in PHP object-oriented? and the role of abstract classes. For more information, please follow other related articles on the PHP Chinese website!