返回 类的继承与重载...... 登陆

类的继承与重载总结

1Pong 2018-12-07 14:24:27 230

本章主要学习了类的继承,以及如何使用范围解析符,并学习了使用static关键字定义静态成员和静态类,通过static关键字实现后期静态绑定,最后学习了类的属性和方法的重载。通过学习,对本章进行练习,代码如下:

主调用页面:chapter4-2.php

<?php

//自动加载类
spl_autoload_register(function ($className){
    require $className . '.php';
});

//使用管理员访问
echoApple('admin');

echo '<hr>';

//使用普通用户访问
echoApple('zhangs');


function echoApple($userID)
{
    $apple=new Apple('日本进口苹果','苹果',15.00);
    echo '店名:',$apple->getDianMing(), ',品牌:',$apple->brand,',名称:',$apple->name,',价格:',$apple->getPrice(),',采购价:',$apple->getInPrice($userID),',老板:',Apple::getBossName($userID),',标语:',Apple::getBiaoYu();
    echo '<br>通过方法重载获取位置:',$apple->getShow('金新北路','汕头市');
}

Fruit.php

<?php

class Fruit
{
    public $brand='特产水果';
    public $name='水果';
    protected  $price=10.00;
    private $inPrice;
    const DIANMING='百果园';
    protected  static  $bossName='1Pong';
    protected  static  $biaoYu='多吃水果';

    public  function  __construct($brand,$name,$price)
    {
        $this->brand=$brand;
        $this->name=$name;
        $this->price=$price;
    }

    //获取进货价
    public  function  getInPrice($userID)
    {
        $reValue='';
        if(strtolower($userID)==='admin')
        {
            $reValue=$this->price * 0.3 . '';
        }
        else
        {
            $reValue='保密';
        }

        return $reValue;
    }
    //获取老板名称
    public  static  function  getBossName($userID)
    {
        $reValue='';
        if(strtolower($userID)==='admin')
        {
            $reValue= static::$bossName;
        }
        else
        {
            $reValue='保密';
        }

        return $reValue;
    }
    //获取商品单价
    public  function  getPrice()
    {
        return $this->price;
    }
    //获取宣传标语
    public  static  function  getBiaoYu()
    {
        return static::$biaoYu;
    }
}

Apple.php

<?php

require 'HelpClass.php';

class Apple extends Fruit
{
    public  $brand='新疆大苹果';
    public  $name='苹果';
    protected $price=5.00;
    protected  static  $biaoYu='an apple a day keep the doctor away';

    public  function  __construct($brand, $name, $price)
    {
        parent::__construct($brand, $name, $price);
    }

    //获取店名
    public  function  getDianMing()
    {
        return parent::DIANMING;
    }

    //通过重载获取HelpClass的getShow方法
    public  function  __Call($method,$arguments)
    {
        return call_user_func_array([(new HelpClass),'getShow'],$arguments);
    }

}

HelpClass.php

<?php

class HelpClass
{
//获取位置
public function getShow($arguments)
{
    $place=func_get_arg(0);
    $city=func_get_arg(1);
    return $city.$place;
}

}

执行效果图:

QQ截图20181207142220.jpg

最新手记推荐

• 用composer安装thinkphp框架的步骤 • 省市区接口说明 • 用thinkphp,后台新增栏目 • 管理员添加编辑删除 • 管理员添加编辑删除

全部回复(0)我要回复

暂无评论~
  • 取消 回复 发送
  • PHP中文网