用spl_autoload_register实现类的自动的加载

Original 2019-03-26 13:16:24 194
abstract:// public目录和spl_autoload.php文件在同一个目录,pupblic目录下有三个文件,分别是Base.php,Computer.php,Mobile.php//spl_autoload.php文件内容:<?phpspl_autoload_register(function ($className) {   require __DIR__."/

// public目录和spl_autoload.php文件在同一个目录,pupblic目录下有三个文件,分别是Base.php,Computer.php,Mobile.php

//spl_autoload.php文件内容:

<?php


spl_autoload_register(function ($className) {

   require __DIR__."/public/{$className}.php"; //推荐绝对路径。

});

$com = new Computer('联想', '扬天', 5000);

$mobile = new Mobile('华为', 'P20', 7800);

$com->show();

$mobile->show();

//Base.php文件内容:

<?php


class Base

{

public function show()

{

echo $this->brand.$this->model.'的价格:'.$this->price, '<hr>';

}

}

//Computer.php文件内容:

<?php


class Computer extends Base

{

public $brand;

public $model;

public $price;


public function __construct($brand, $model, $price)

{

$this->brand = $brand;

$this->model = $model;

$this->price = $price;

}

}


//Mobile文件内容:

<?php


class Mobile extends Base

{

public $brand;

public $model;

public $price;


public function __construct($brand, $model, $price)

{

$this->brand = $brand;

$this->model = $model;

$this->price = $price;

}

}


Correcting teacher:天蓬老师Correction time:2019-03-26 16:45:08
Teacher's summary:其实这个案例,已经设计到一些初步的设计模式的知识啦

Release Notes

Popular Entries