What is the usage of extends in php

WBOY
Release: 2023-03-15 22:02:02
Original
3639 people have browsed it

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.

What is the usage of extends in php

The operating environment of this article: Windows 10 system, PHP version 5.6, Dell G3 computer

What is the usage of extends in php

In PHP, class inheritance needs to be implemented through the extends keyword. The syntax format is as follows:

class 子类名 extends 父类名{
    ... ...
}
Copy after login

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:

What is the usage of extends in php

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

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!

Related labels:
php
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