spl_autoload_register()的require问题

 
目录结构
dir
 
AA.php
<?php
class AA
{
public function aaa()
{
echo 'aaaa';
}
}

 

bb.php

<?php

class BB
{
function bbb()
{
echo 'bbbb';
}
}
 
index.php
<?php
spl_autoload_register('autoloader1');
spl_autoload_register('autoloader2');
$a = new AA();
$a->aaa();
$b = new BB();
$b->bbb();
function autoloader1($class)
{
//include will be ok
require 'Z/A/' . $class . '.php';
}
function autoloader2($class)
{
//include will be ok
require 'Z/B/' . $class . '.php';
}

 

结果只加载和执行了了第一个文件,第二个文件加载出错

error1

 

第二个autoload函数未执行,因此提示未找到BB.php文件

error

 

解决办法:

但是在autoloader函数中加一句文件是否存在的判断,就可以自动加载了

function autoloader1($class)
{
$file = 'Z/A/' . $class . '.php';
//file_exists is ok, too
if(is_readable($file)) {
require $file;
}
}
function autoloader2($class)
{
$file = 'Z/B/' . $class . '.php';
//is_readable is ok, too
if(file_exists($file)) {
require $file;
}
}

 

ok

 

不知道为什么,是文件缓存之类的嘛转动眼睛

posted @ 2015-12-27 15:28  物理挂了  阅读(486)  评论(0编辑  收藏  举报