Home >Backend Development >PHP Tutorial >Detailed explanation of inheritance and usage examples of classes in PHP
This article mainly introduces the inheritance and usage of classes in PHP. It analyzes the inheritance methods, usage methods and related precautions of classes in PHP in more detail. Friends in need can refer to it
1. Inheritance keyword: extends
Inheritance of PHP class, we can understand it as sharing the content of the inherited class. Please avoid using the extends single inheritance method in PHP! (Non-C multiple inheritance) The inherited class is called the parent class (base class) and the inheritor becomes the subclass (derived class).
2. PHP inheritance rules
CLASS1------>CLASS2------>CLASS3
are inherited in turn. class3 has all the functions and attributes of class1 and class2 to avoid duplicate names of methods and attributes.
class Son{} inherits class root{};
class Son extends Root{};
3. Base class method overloading and parent class method access
Because it belongs to Under the principle of inheritance, the base class cannot use the content in the derived class. At this time, some methods of the base class cannot complete the functions of some of our derived classes. We can overload methods to avoid the confusion caused by new methods.
Method overloading We can also understand method overriding, which is to perform overloading in a derived class using a method name that has the same name as a base class method.
When overloading, we need to call the original base class content and add new content. We can use
base class name:: method name.
Example:
<?php class Root{ function dayin(){ return "Root print <br />"; } } class Son extends Root{ function dayin(){ //return $this->dayin()."Son print <br/>"; return Root::dayin()."Son print <br />"; } } $s=new Son(); echo $s->dayin(); ?>
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.
Related recommendations:
phpSimple configuration method of error log
PHP implementation detects whether the URL can be opened normally Method
PHP method to implement simple encryption technology
The above is the detailed content of Detailed explanation of inheritance and usage examples of classes in PHP. For more information, please follow other related articles on the PHP Chinese website!