'use'关键字会触发PHP自动加载吗? [英] Does the 'use' keyword trigger autoloading in PHP?

查看:246
本文介绍了'use'关键字会触发PHP自动加载吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,自动加载器在什么时候加载类文件(如果有的话)?例如,如果$boolean_test === false是否加载了子包?

In the example below, at what point does the autoloader load the class file, if at all? For example, if $boolean_test === false does the Subpackage get loaded?

use Org\Group\Package\Subpackage; // autoloader triggered here?
if ($boolean_test) {
    Subpackage::method(); // or here?
}

我更喜欢代码顶部附近的use语句,因此我可以看到页面中使用了哪些软件包,并且可读性更好.但是,如果仅根据条件使用软件包,则可能正在加载不需要的资源.

I prefer the use statement near the top of the code so I can see what packages are used in the page and for slightly better readability. But, if packages are only used based on conditionals, I may be loading unneeded resources.

推荐答案

use不会触发自动加载.您可以在文件顶部添加一个无效的use,PHP不会抱怨.

No use does not trigger autoloading. You can have an invalid use at the top of your file and PHP won't complain.

当您尝试使用该类时,会发生自动加载.

Autoloading happens when you attempt to use the class.

对此进行测试非常容易: https://3v4l.org/OccF3

It's quite easy to test this: https://3v4l.org/OccF3

这篇关于'use'关键字会触发PHP自动加载吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆