dongyixun0634 2015-11-30 08:34
浏览 37
已采纳

这个spl_autoload_register是如何工作的

I'm studying on spl_autoload_register(). I know what it is for ,just wondering how to use it practically. I searched for few references over the net for these, and each one has it's own style of approach. However I'm interested to understand the below script which found in one of my ebook.

WHat these three lines doing, I can understand roughly but not exactly. The autoload function receives a parameter $class, but why the below not dealing with it at all? For which class or item its defining the path?

1) get_include_path()

2) What is this doing? $flags = PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE;

         $paths = explode(PATH_SEPARATOR, get_include_path());
         $flags = PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE;
         $file = strtolower(str_replace("\\", DIRECTORY_SEPARATOR, trim($class, "\\"))).".php";

Script

function autoload($class)
{

     $paths = explode(PATH_SEPARATOR, get_include_path());
     $flags = PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE;
     $file = strtolower(str_replace("\\", DIRECTORY_SEPARATOR, trim($class, "\\"))).".php";

 foreach ($paths as $path)
 {
 $combined = $path.DIRECTORY_SEPARATOR.$file;
 if (file_exists($combined))
 {
 include($combined);
 return;
 }
 }
 throw new Exception("{$class} not found");
}
class Autoloader
{
 public static function autoload($class)
 {
 autoload($class);
 }
}
spl_autoload_register('autoload');
spl_autoload_register(array('autoloader', 'autoload'));
// these can only be called within a class context…
// spl_autoload_register(array($this, 'autoload'));
// spl_autoload_register(__CLASS__.'::load');
  • 写回答

1条回答 默认 最新

  • drjyvoi734793 2015-11-30 09:00
    关注

    The function spl_autoload_register is called with parameter 'autoload'. That makes the function autoload to be called whenever a class is not found.

    When a class is not found, then the function autoload is invoked with the faulty class name as its parameter, and that parameter is actually used in its third line.

    $file = strtolower(str_replace("\\", DIRECTORY_SEPARATOR, trim($class, "\\"))).".php";
    

    It is used to try to find a file with the same name as the class (Faulty class => Faulty.php file) in any of the directories returned by core function get_include_path.

    The only odd thing is that the $flags variable was set to be included as one of the parameters for the str_replace function they are actually not used at all; but I don't know if they are really needed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法