惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The GitHub Blog
The GitHub Blog
雷峰网
雷峰网
小众软件
小众软件
博客园 - 【当耐特】
J
Java Code Geeks
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Hugging Face - Blog
Hugging Face - Blog
腾讯CDC
Engineering at Meta
Engineering at Meta
aimingoo的专栏
aimingoo的专栏
A
About on SuperTechFans
H
Help Net Security
博客园_首页
P
Proofpoint News Feed
GbyAI
GbyAI
大猫的无限游戏
大猫的无限游戏
N
Netflix TechBlog - Medium
爱范儿
爱范儿
MyScale Blog
MyScale Blog
Blog — PlanetScale
Blog — PlanetScale
The Cloudflare Blog
MongoDB | Blog
MongoDB | Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Google DeepMind News
Google DeepMind News

博客园 - yiyide266

[Express.js]next()函数的作用 [css]浏览器默认样式 have的实质 This comes after Chinese authorities announced an investigation against Mayday, in response to a viral video. [Linux]终端ssh远程连接如何保持 [PHP]PDO的dsn对mysql的连接影响 [PHP]回调函数参数(callable类型)的一些细节 [javascript]端序(endian)和Buffer对象的read|write系列函数 vscode处理HTML标签两个光标的问题 intend,intent和indent [css]一个块格式化上下文(BFC)阻止外边距重叠的示例 [PHP_yaf]内部注册到spl_autoload的方法 [PHP_yaf]Yaf_Application [PHP_yaf]写在用户代码的配置项 [PHP_yaf]保存在php.ini中的配置项 [英语单词]关于战争 [MySql]1820错误码重置密码方法 [Linux]信号捕捉函数总是第一时间执行 [Linux]信号捕捉函数与exec
[PHP]spl_autoload函数栈的向下遍历机制
yiyide266 · 2022-04-10 · via 博客园 - yiyide266

问题

倘若利用spl_autoload_register注册多个autoload_function,spl_autoload机制在自动加载的时候是否会由上至下把所有注册的函数运行一遍呢?

真相

看看如下例子:

<?php
function autoload_01()
{
    var_dump("autoload_01");
    spl_autoload("foo");
}
function autoload_02()
{
    var_dump("autoload_02");
    spl_autoload("foo");
}
spl_autoload_register("autoload_01");
spl_autoload_register("autoload_02");

new foo();

假设当前include目录下存在foo,那么输出结果如下:

/mnt/hgfs/lroot/www/10002/test_51.php:4:string 'autoload_01' (length=11)

即使把spl_autoload函数换成include,效果也是一样的:

<?php
function autoload_01()
{
    var_dump("autoload_01");
    include("foo.php");
}
function autoload_02()
{
    var_dump("autoload_02");
    include("foo.php");
}
spl_autoload_register("autoload_01");
spl_autoload_register("autoload_02");

new foo();

但是如果当前include_path不存在foo,那么输出结果就会如下:

/mnt/hgfs/lroot/www/10002/test_51.php:4:string 'autoload_01' (length=11)
/mnt/hgfs/lroot/www/10002/test_51.php:9:string 'autoload_02' (length=11)
Fatal error: Uncaught Error: Class 'foo' not found in ?.php on line ?

以上说明当其中一个注册函数找到类文件,则不再执行余下注册函数,否则继续运行下面的注册函数,直到找到类为止

那么,让注册函数返回布尔值是否能阻止函数继续向下运行呢?答案是不能

修改一下以上例子:

<?php
function autoload_01()
{
    var_dump("autoload_01");
    return true;
    //return false;
}
function autoload_02()
{
    var_dump("autoload_02");
}
spl_autoload_register("autoload_01");
spl_autoload_register("autoload_02");

new foo();

无论autoload_01返回TRUE还是FALSE,都不影响PHP往下执行autoload_01:

/mnt/hgfs/lroot/www/10002/test_51.php:4:string 'autoload_01' (length=11)
/mnt/hgfs/lroot/www/10002/test_51.php:10:string 'autoload_02' (length=11)
 Fatal error: Uncaught Error: Class 'foo' not found in ? on line ?