[PHP] 纯文本查看 复制代码 <?php
class Person{
protected $name, $age, $sex;
// 构造函数(即为初始化方法,通过类名括号传参数)
function __construct($name, $age, $sex){
$this->name = $name;
$this->age = $age;
$this->sex = $sex;
}
function say(){
return "(名字:{$this->name})、(年龄:{$this->age})、(性别:{$this->sex})";
}
function eat(){
echo "eating ....<br/>";
}
function run(){
}
}
class Student extends Person{
private $school;
// 相同名字方法即为覆盖
function __construct($name, $age, $sex, $school){
// 先调用父类方法,再扩展子类特性
parent::__construct($name, $age, $sex);
$this->school = $school;
}
function study(){
}
function say(){
return parent::say()."、(学校:{$this->school})";
}
}
class Teacher extends Person{
function teach(){
}
}
$person = new Person("rose", 22, "女");
echo $person->say()."<br/>";
$student = new Student("jake", 24, "男", "林大");
echo $student->say()."<br/>";
运行结果:
(名字:rose)、(年龄:22)、(性别:女)
(名字:jake)、(年龄:24)、(性别:男)、(学校:林大) |