php自动加载是干嘛的,php – 这个自动加载功能如何?

标签:php

这是我的自动装载机课程.我从本周开始学习PHP.我从不同的文章和PHP动作书中得到了自动加载器的想法,但我不知道它实际上是如何运作的?

class autoloader {

public static $loader;

public static function init()

{

if(self::$loader == NULL) {

self::$loader = new self();

}

return self::$loader;

}

public function __construct()

{

spl_autoload_register(array(this, 'library'));

spl_autoload_register(array(this, 'controller'));

spl_autoload_register(array(this, 'helper'));

spl_autoload_register(array($this, 'model'));

}

public function library($class)

{

set_include_path(get_include_path() . PATH_SEPARATOR . '/lib');

spl_autoload_extensions('.php');

spl_autoload($class);

}

public function controller($class)

{

set_include_path(get_include_path() . PATH_SEPARATOR . '/controller');

spl_autoload_extensions('.php');

spl_autoload($class);

}

public function helper($class)

{

set_include_path(get_include_path() . PATH_SEPARATOR . '/helper');

spl_autoload_extensions('.php');

spl_autoload($class);

}

public function model($class)

{

set_include_path(get_include_path() . PATH_SEPARATOR . '/model');

spl_autoload_extensions('.php');

spl_autoload($class);

}

}

我想问一下这款自动加载器的功能究竟如何?

例如,如果我实现了一个位于lobrary文件夹下的类

如何处理这个完整的文件?

解决方法:

首先,当您实例化一个类时,它的构造函数会注册四个函数来处理类自动加载.

$autoloader = new autoloader();

他们每个人都会在自己的特定目录中查找文件.无需调用autoloader :: init()函数,因为所有自动加载函数都已通过实例化类注册.

然后,当你尝试实例化一个类时,如果PHP无法找到它,那么在失败之前它将运行函数,由spl_autoload_register()按照它们注册的顺序注册. (autoloader :: library(),autoloader :: controller(),autoloader :: helper()和autoloader :: model()),如果在该类可用之后,它将被实例化.

扩展您的示例,这里是一些代码片段:

include 'autoloader.php'; // in this file we have our autoloader class

$autoloader = new autoloader();

$libClass = new someLib();

当我们调用new someLib()时,PHP的自动加载机制将在include_path指令中提到的所有区域中查找文件’somelib.php'(!lowercase!).你看,每个函数都为这个指令添加了自己的位置

set_include_path(get_include_path() . PATH_SEPARATOR . '/controller');

这意味着名为“controller”的文件夹(位于根目录中)将添加到include_path中,然后spl_autoload()将在其中查找文件.所以你必须创建文件/lib/somelib.php并拥有一个名为’someLib’的类

希望这可以帮助

标签:php

来源: https://codeday.me/bug/20190626/1293815.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值