Home >Backend Development >PHP Problem >What is the usage of extends in php
In PHP, the extends keyword is used to define the inheritance of a class. The syntax is "class subclass extends parent class {}"; through this keyword, single inheritance can be achieved, and one class can only directly inherit from another class. Data is inherited in classes, but a class can have multiple subclasses.
The operating environment of this article: Windows 10 system, PHP version 5.6, Dell G3 computer
In PHP, class inheritance needs to be implemented through the extends keyword. The syntax format is as follows:
class 子类名 extends 父类名{ ... ... }
In C, a subclass can inherit one base class or multiple base classes. Inheriting one base class is called single inheritance; inheriting multiple base classes is called multiple inheritance. But there is no multiple inheritance in PHP, only single inheritance mode can be used. That is, a class can only directly inherit data from another class. But a class can have multiple subclasses.
Member properties and methods in a class need to be modified with access modifiers, which is an important feature in PHP object-oriented programming. The functions of different access modifiers and the differences between them are shown in the following table:
The example is as follows:
<?php class Person { var $name; var $age; function say() { echo "我的名字叫:".$this->name."<br />"; echo "我的年龄是:".$this->age; } } // 类的继承 class Student extends Person { var $school; //学生所在学校的属性 function study() { echo "我的名子叫:".$this->name."<br />"; echo "我正在".$this->school."学习"; } } $t1 = new Student(); $t1->name = "张三"; $t1->school = "人民大学"; $t1->study(); ?>
Run this example, the output is:
My name is: Zhang San
I am studying at Renmin University
Recommended study: "PHP Video Tutorial"
The above is the detailed content of What is the usage of extends in php. For more information, please follow other related articles on the PHP Chinese website!