搜索

独立完成类的自动加载案例,从此告别include/require

原创 2019-03-24 21:01:13 359
摘要:// public/Mobile.php <?php class Mobile {     public $brand; //品牌     public $model; //型号     public 
// public/Mobile.php
<?php

class Mobile
{
    public $brand; //品牌
    public $model; //型号
    public $price; //价格

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

// demo3.php
<?php
spl_autoload_register(function($className){
    require __DIR__.'/public/'.$className.'.php';
});
$mobile = new Mobile('小米','xiaomi9',7800);
echo $mobile->brand.$mobile->model.':'.$mobile->price,'<br>';

自动加载器spl_autoload_register()利用回调函数和绝对路径字符串拼接实现自动加载类,可以大大提升加载的效率。

QQ图片20190324205754.png

批改老师:查无此人批改时间:2019-03-25 09:21:16
老师总结:完成的不错。这个截图我好像看到过,又是你吧。继续加油

发布手记

热门词条