What is class inheritance? To put it bluntly, I think it is to improve the efficiency of code usage. Now I will introduce inheritance to you.
The concept of class inheritance
The subclass inherits all member variables and methods of the parent class, including the construction method. When the subclass is instantiated, PHP will Query the constructor method in the class. If the subclass has its own constructor, PHP will first call the method in the subclass; when there is no constructor in the subclass, PHP will call the constructor method in the parent class. This is what we call inheritance. .
The inheritance of a class is through the keyword extends, and the syntax is:
class A extends B{ ... }
A represents the subclass, and B represents the parent class.
Okay, now that we understand the basic concepts, let’s look at the inheritance examples of classes:
First create a class, which has different methods:
<?php //父类 class Lol{ public $name; public $type; public $price; public function __construct($name,$price){ $this->name = $name; $this->price = $price; } function ShowInfo(){ echo "在这不显示"; } } //子类Play class Play extends Lol{ //定义子类,继承父类 public $type; //在子类中定义变量 public function __construct($name,$type){ $this->name = $name; $this->type = $type; } function ShowInfo(){ if($this->type == "mid"){ return $this->name . "会玩这个位置"; }else{ return $this->name . "不会玩这个位置"; } } } //实例化对象 $player = new Play("faker","mid"); echo $player->ShowInfo();
The above is the detailed content of PHP object-oriented: class inheritance examples explained. For more information, please follow other related articles on the PHP Chinese website!