Blogger Information
Blog 31
fans 3
comment 1
visits 34400
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
父类与子类,类的继承与方法重写
php学习笔记
Original
1061 people have browsed it

1.创建父类电脑类:Computer

<?php
/**
 * 创建父类电脑类:Computer
 */

class Computer
{
    protected $brand;
    protected $price;
    //构造方法
    public function __construct($brand,$price)
    {
        $this->brand = $brand;
        $this->price = $price;
    }

    public function internet()
    {
        return '能上网';
    }

}

2.创建子类笔记本电脑类:Notebook

<?php
/**
 * 创建子类笔记本电脑类:Notebook
 * 类Notebook继承自Computer类
 */

class Notebook extends Computer
{
    //创建查询器
    public function __get($name)
    {
        return $this->$name;
    }
    private $portable = false;//是否便于携带

    public function __construct($brand, $price,$portable)
    {
        parent::__construct($brand, $price);
        $this->portable = $portable;
    }
    //对父类方法进行重写
    public function internet()
    {
        return parent::internet().',而且体积小便于携带';
    }
}

3.创建一个测试的php脚本

<?php
//自动加载类
spl_autoload_register(function($className){
    require 'class/'.$className.'.php';
});
$notebook = new Notebook('联想','5888','true');
echo '品牌:'.$notebook->brand.'<br>';
echo '价格:'.$notebook->price.'<br>';
echo '是否可携带:'.($notebook->portable?'是':'否').'<br>';
echo $notebook->internet().'<br>';

运行结果:

运行结果.png


Correction status:qualified

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