6.创建一个PHP文件,首先声明一个Person类,然后以Person作为基类来创建派生类Student,要求在派生类中增加一些新的属性。
时间: 2023-11-28 21:49:43 浏览: 33
以下是创建一个PHP文件,声明一个Person类,并以Person作为基类来创建派生类Student的示例:
```php
<?php
// Person class
class Person {
public $name;
public $age;
function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
function introduce() {
echo "My name is " . $this->name . " and I am " . $this->age . " years old.";
}
}
// Student class derived from Person class
class Student extends Person {
public $major;
function __construct($name, $age, $major) {
parent::__construct($name, $age);
$this->major = $major;
}
function introduce() {
echo "My name is " . $this->name . " and I am " . $this->age . " years old. " . "My major is " . $this->major . ".";
}
}
// Create objects
$person = new Person("John", 30);
$student = new Student("Jane", 20, "Computer Science");
// Call methods
$person->introduce();
echo "<br>";
$student->introduce();
?>
```
在上面的示例中,Person类有两个属性$name和$age,一个构造函数__construct()和一个介绍方法introduce()。Student类是从Person类派生出来的,具有一个新属性$major,并重写了介绍方法introduce()。在Student类的构造函数中,调用了基类的构造函数,以便初始化$name和$age属性。创建了一个Person对象和一个Student对象,并调用它们的介绍方法introduce()。输出如下:
```
My name is John and I am 30 years old.
My name is Jane and I am 20 years old. My major is Computer Science.
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)