PHP object-oriented: class inheritance examples explained

巴扎黑
Release: 2023-03-07 11:32:01
Original
2728 people have browsed it

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{
...
}
Copy after login

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();
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!