Blogger Information
Blog 48
fans 2
comment 3
visits 37857
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
5月3日作业—类的继承与方法重载
黑猫警长的博客
Original
914 people have browsed it

实例

<?php

/* 
 * 类的继承与方法重载
 * 
 */

spl_autoload_register(function($className){
    require './class/'.$className.'.php'; 
});

$nut = new Nut('花生','坚果类', 10,false,true);
echo '水果名: '.$nut->name.'<br>'; 
echo '类型: '.$nut->model.'<br>'; 
echo '价格: '.$nut->price. '<br>';
echo '能否扦插:'.($nut->qiancha?'能':'不能').'<br>';
echo '是否去壳:'.($nut->guoke?'要':'不用').'<br>';

echo $nut->eat().'<br>'; 
echo $nut->oils().'<br>';

运行实例 »

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

父类

<?php

/**
 * 创建水果类:Fruit
 */
class Fruit
{

    protected $name;
    protected $model;
    protected $price;
    
    //构造方法
    public function __construct($name,$model,$price)
    {
        $this->name = $name;
        $this->model = $model;
        $this->price = $price;
    }
    
    public function eat()
    {
        return '休闲食品';
    }
}

运行实例 »

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

子类

<?php

class Nut extends Fruit
{ 
    //创建查询器,实现了外部访问
    public function __get($name)
    {
        return $this->$name;
    }
    
    private $qiancha = false;  
    private $guoke = false; 
    
    //必须使用构造方法对使用当前新增属性生效
    public function __construct($name,$model,$price,$qiancha,$guoke)
    {
        parent::__construct($name, $model, $price);      
        $this->qiancha = $qiancha;
        $this->guoke = $guoke;
    }
    
    //2.增加新的方法,扩展父类的功能
    public function oils()
    {
        return '能榨油';
    }
    
    //3.将父类方法进行重写,就是功能重载,必须使用与父类一样的方法名:call()
    public function eat()
    {
        // return ',能下酒';
        //那么,如何在子类中引用父类中的方法呢? 使用关键字: parent,后面跟上双冒号::
        return parent::eat().',能下酒';
    }
    
    
    
}

运行实例 »

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

QQ截图20180513173826.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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!