Blogger Information
Blog 48
fans 0
comment 0
visits 36363
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
类的继承、多态与方法重写-2018.09.03
雨天的博客
Original
631 people have browsed it

实例

<?php
/**
 * 继承与多态
 * 1.继承是类之间的继承,是代码服用的重要手段,之前的代码服用有“函数”;
 * 2.父类中的公共成员和受保护的成员子类全部继承
 *继承的关键字 extends
 * 子类调用父类的成员 parent::
 */
class Demo4{
    const  SITE_NAME = 'PHP编程语言';
    protected $name;
    protected $sex;
    function __construct($name,$sex)
    {
        $this->name = $name;
        $this->sex = $sex;
    }
    //属性重载
    function __get($name)
    {
        if($name == 'sex')
        {
            return false;
        }
        return $this->$name;
    }

}
class Demo4_1 extends Demo4{
    const SITE_NAME = '编程语言';
    private $age;
    //子类重写父类的方法,实现不同的功能 这叫做多态
    function __construct($name, $sex,$age='18')
    {
        parent::__construct($name, $sex);//子类调用父类的构造方法
        $this->age = $age;
    }
    //属性重载
    function __get($name)
    {
       if($name == 'sex')
        {
            return false;
        }
       return $this->$name;
    }

}
$demo = new Demo4_1('SHE','女');
echo Demo4::SITE_NAME.'<br>';//父类访问类常量
echo Demo4_1::SITE_NAME.'<br>';//子类访问类常量
//访问父类的属性
echo $demo->sex;
echo $demo->name.'<br>';
//访问私有属性
echo $demo->age;

运行实例 »

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


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!