以下是一个简单的PHP类实例,其中包含了一个用于计算年龄的方法。我们将通过一个表格来展示类的定义、方法的使用以及如何创建类的实例。
| 类定义 | 使用方法 | 实例化类 |
|---|
| ```php |
class Person { public $name;

public $birthdate;
public function __construct($name, $birthdate) {
$this->name = $name;
$this->birthdate = $birthdate;
}
public function calculateAge() {
$today = new DateTime();
$birthdate = new DateTime($this->birthdate);
$age = $birthdate->diff($today)->y;
return $age;
}
}
```
| ```php |
// 创建类实例$person = new Person('John Doe', '1990-05-15');
// 调用方法
$age = $person->calculateAge();
// 输出结果
echo 'John Doe is ' . $age . ' years old.';
```
| ```php |
// 实例化$person = new Person('Jane Smith', '1985-10-20');
// 使用
$age = $person->calculateAge();
// 输出
echo 'Jane Smith is ' . $age . ' years old.';
``` |
在这个例子中,我们定义了一个名为`Person`的类,它有两个属性:`name`和`birthdate`。`__construct`方法用于在创建类的实例时初始化这些属性。`calculateAge`方法用于计算并返回一个人的年龄。
在`使用方法`部分,我们展示了如何创建`Person`类的实例,并调用其`calculateAge`方法来获取年龄,然后输出结果。
在`实例化类`部分,我们展示了如何为不同的个人创建`Person`类的实例,并调用`calculateAge`方法来获取他们的年龄。