一、继承与扩展
1.子类使用extends继承父类,子类可以将父类所有内容继承,如下:
//多层继承
class Person {
var $name;
var $age;
var $sex;
function __construct(){
}
function say(){
}
function eat(){
echo "1111";
}
function run(){
}
};
class Student extends Person {
var $school;
function __construct(){
}
function study(){
}
};
class Teacher extends Student {
var $gz;
function teach(){
}
};
$stu=new Student;
$stu->eat();
/1111
2.private无法继承给子类,如下:
class Person {
private $name="liu";
var $age;
var $sex;
function __construct(){
}
function say(){
echo $this->name;
}
function eat(){
echo "1111";
}
function run(){
}
};
class Student extends Person {
var $school;
function __construct(){
}
function study(){
}
};
class Teacher extends Student {
var $dw;
function teach(){
echo $this->name;
}
};
$teacher=new Teacher;
$teacher->say();//liu 只是子类引用继承了父类的say()
$teacher->teach();//error
3.protected保护权限,只能自己和子类使用,外部无法读取,如下:
class Person {
private $name="liu";
protected $age=10;
var $sex;
function __construct(){
}
function say(){
echo $this->age;
}
function eat(){
echo "1111";
}
function run(){
}
};
class Student extends Person {
var $school;
function __construct(){
}
function study(){
}
};
class Teacher extends Student {
var $dw;
function teach(){
echo $this->age;
}
};
$teacher=new Teacher;
$teacher->say();//10
$teacher->teach();//10
4.public(默认)公开权限,所有位置都可用,不再重复举例,各权限如下图:
二、继承中的重载/覆盖
1.强类型语言中重载:方法名相同,参数或参数个数不同
2.弱类型语言理解为覆盖:同一类中同名方法后覆盖前
3.弱类型中的重载:子类里可以写与父类同名的方法,即方法的扩展(接口、多态)
4.调用类的方法Person::say();
5.调用父类(被覆盖)的方法(默认关键字)parent::say();
6.__construct()也可以覆盖,但最开始必须调用父类构造函数,如下:
function __construct($name,$age,$sex,$school){
//先调用父类构造方法,否则父类初始化后,子类不变
parent::__construct($name,$age,$sex);
$this->school=$school;
}
7.权限:子类权限只能>=父类权限,即public > protected > private
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。