搜索

类的自动加载案例

原创 2019-04-02 21:36:59 230
摘要:基本思路:    创建了一个Superhero以及Car这两个类,在源程序中通过spl_autoload_register以及require方法对其调用,完成了类的自动加载的两个案例.完整代码:Superhero类<?php /**  * Created by PhpStorm.  * Use

基本思路:

    创建了一个Superhero以及Car这两个类,在源程序中通过spl_autoload_register以及require方法对其调用,完成了类的自动加载的两个案例.

完整代码:

Superhero类

<?php
/**
 * Created by PhpStorm.
 * User: hp
 * Date: 2019/4/2
 * Time: 21:13
 */

class Superhero
{
    public $name = '钢铁侠';
    public $age = '45';
    private $salary = '90000$元';

    public function getSalary()
    {
        $res = $this->salary;
        if ($this->name == '钢铁侠')
        {
            $res = '超级英雄的工资不是你能随便看的!';
        }
        return $res;
    }
}

Car类:

<?php
/**
 * Created by PhpStorm.
 * User: hp
 * Date: 2019/4/2
 * Time: 21:25
 */
class Car
{
    public $brand = '凯迪拉克';
    public $model = '40T';
    public $price = 699000;
}

源码部分:

<?php
/**
 * Created by PhpStorm.
 * User: hp
 * Date: 2019/4/2
 * Time: 21:00
 */
spl_autoload_register(function ($ClassName)
{
    require './public/'.$ClassName.'.php';
});
$Superhero = new Superhero;
echo $Superhero->name.'的年龄是'.$Superhero->age.'岁,薪水是'.$Superhero->getSalary();
echo '<br>';
$Car = new Car();
echo $Superhero->name.'购买了一辆'.$Car->brand.$Car->model.',价格是'.$Car->price.'美元!!!';


批改老师:天蓬老师批改时间:2019-04-03 13:15:41
老师总结:类的自动加载与命名空间配合, 才会发挥最大的作用, 后面的命名 空间知识要好好学一下

发布手记

热门词条