php定义一个学生类_定义person类及其子类,并按要求设计、定义和实例化类 (实例)...
时间: 2024-02-17 14:00:24 浏览: 22
好的,我来帮您解答这个问题。
首先,我们来定义一个 `Person` 类,它包含 `name` 和 `age` 两个属性,以及 `sayHello` 方法:
```php
class Person {
public $name;
public $age;
public function sayHello() {
echo "Hello, my name is {$this->name} and I am {$this->age} years old.\n";
}
}
```
接下来,我们来定义 `Student` 类,它继承自 `Person` 类,并增加一个 `major` 属性和一个 `study` 方法:
```php
class Student extends Person {
public $major;
public function study() {
echo "{$this->name} is studying {$this->major}.\n";
}
}
```
现在,我们已经定义了 `Person` 和 `Student` 两个类,接下来我们可以实例化它们:
```php
// 创建一个 Person 对象
$person = new Person();
$person->name = "Alice";
$person->age = 20;
$person->sayHello(); // 输出:Hello, my name is Alice and I am 20 years old.
// 创建一个 Student 对象
$student = new Student();
$student->name = "Bob";
$student->age = 18;
$student->major = "Computer Science";
$student->sayHello(); // 输出:Hello, my name is Bob and I am 18 years old.
$student->study(); // 输出:Bob is studying Computer Science.
```
以上就是一个简单的示例,展示了如何定义 `Person` 和 `Student` 两个类,并实例化它们。