通过继承,子类可以重复使用父类的属性和方法,再另外定义自己的属性和方法,通过代码复用,提高了编程效率。
语法:
class ChildClass extends FatherClass{ //子类代码 }
示例:
class User{ private $name; private $grade; private $class; //__get()方法获取属性值 public function __get($propertyName){ return $this->$propertyName; } //__set()方法设置属性值 public function __set($propertyName,$value){ $this->$propertyName = $value; } } class Student extends User { protected $score;//定义子类的变量 } class Teacher extends User { protected $phoneNum;//定义子类的变量 } $stu = new Student(); $stu->name = 'zhangsan'; $stu->grade = '2015级'; $stu->class = '1班'; $stu->score = '100'; $teacher = new Teacher(); $teacher->name = 'lisi'; $teacher->grade = '2015级'; $teacher->class = '2班'; $teacher->phoneNum = '13312345678'; var_dump($stu); var_dump($teacher);
运行效果:
object(Student)[1] protected 'score' => string '100' (length=3) private 'name' (User) => string 'zhangsan' (length=8) private 'grade' (User) => string '2015级' (length=7) private 'class' (User) => string '1班' (length=4) object(Teacher)[2] protected 'phoneNum' => string '13312345678' (length=11) private 'name' (User) => string 'lisi' (length=4) private 'grade' (User) => string '2015级' (length=7) private 'class' (User) => string '2班' (length=4)
通过继承,Student类和Teacher类都不必为相同的属性重复编写代码,属性访问方法也可以从父类继承。
注意:这里子类继承调用了父类的__get()、__set()方法,所以父类的private属性,子类对象也能访问到。同时子类的属性设置为protected,所以父类的__get()、__set()方法也能访问。