Blogger Information
Blog 33
fans 0
comment 2
visits 41923
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP面向对象编程:类的继承
hanyufeng的博客
Original
1111 people have browsed it

通过继承,子类可以重复使用父类的属性和方法,再另外定义自己的属性和方法,通过代码复用,提高了编程效率。

语法:

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()方法也能访问。

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!