Blogger Information
Blog 28
fans 0
comment 0
visits 15818
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
2018-09-03继承
阿小的博客
Original
560 people have browsed it

实例

<?php
//对象三大特征:继承封装,多态
//继承是代码复用的手段,关键字extends

//父类
class Demo
{
    public $name;
    protected $age;
    private $sex;
    const SITE_NAME = 'PHP中文网';
    
    public function __construct($name,$age)
    { 
        $this->name = $name;
        $this->age = $age;
      
    }
    
//     public function __get($name)
//     {
//         if(isset($this->$name)){
//             return $this->$name;
//         }
//         return '非法属性';
//     }
}

//子类
class Demo_1 extends Demo
{
    private $salary;
    //子类中的常量可以重写
    const SITE_NAME = 'PHP.cn';
    //子类的构造方法必须将父类的构造方法重新声明一遍 
    //将父类的方法重写-多态
    public function __construct($name, $age,$salary)
    {
        $this->salary = $salary;
        //访问父类关键字parent
        parent::__construct($name, $age);
    }
    
    public function __get($name)
    {
        if(isset($this->$name)){
            return $this->$name;
        }
        return '非法属性';
    }
}

$demo_1 = new Demo_1('Peter', 28,8000);
echo $demo_1->name.'<br>';
echo $demo_1->age.'<br>';   //私有属性,只能在父类和子类中使用,外部不可使用
echo $demo_1->show.'<br>';     //属性不存在时自动调用__get()方法
echo $demo_1->salary.'<br>';
echo Demo::SITE_NAME.'<br>';
echo Demo_1::SITE_NAME.'<br>';

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:Uncorrected

Teacher's comments:
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