PHP的“使用"关键字和自动加载 [英] PHP's "use" Keyword and Autoloading
问题描述
我的问题分为三个部分:
My question is in three parts:
放入
use
语句是立即触发自动加载器,还是等到类被使用?(延迟加载)
Does putting in a
use
statement trigger the autoloader immediately, or does it wait until the class is used? (lazy-loading)
如果自动加载不是以延迟加载的方式完成,是否会对性能产生负面影响?
If autoloading isn't done in a lazy-load fashion, could that negatively affect performance?
最好遵循哪种模式,为什么?当未使用 use
语句时,PhpStorm 将不必要的完全限定名称..."显示为代码问题.
Which pattern is best to follow, and why? PhpStorm shows "Unnecessary fully qualified name..." as a code issue when the use
statement isn't employed.
以下是带有 use
语句的 Laravel 控制器的示例类定义:
Here's an example class definition for a Laravel controller with a use
statement:
namespace App\Http\Controllers;
use Carbon\Carbon;
class FooController extends Controller
{
/**
* This action uses the Carbon class
*/
public function bar1()
{
return view('foo.bar1', ['now' => new Carbon()]);
}
/**
* This action does not use the Carbon class
*/
public function bar2()
{
return view('foo.bar2');
}
}
没有use
语句的同一个类:
namespace App\Http\Controllers;
class FooController extends Controller
{
/**
* This action uses the Carbon class
*/
public function bar1()
{
return view('foo.bar1', ['now' => new \Carbon\Carbon()]);
}
/**
* This action does not use the Carbon class
*/
public function bar2()
{
return view('foo.bar2');
}
}
推荐答案
1) 当您执行 new Class()
语句时,该类会自动加载.
1) The class is autoloaded when you perform a new Class()
statement.
2) 见 1)
3) 最好遵循哪种模式以及为什么?:
3) Which pattern is best to follow and why?:
我建议使用 use
因为你可能会遇到这样的情况:你的命名空间很长,你的代码会变得不可读.
I'd recommend to use use
because you might get into a situation where you have really long namespaces and your code will become unreadable.
来自 php 文档:
此示例尝试从以下位置加载类 MyClass1 和 MyClass2分别是 MyClass1.php 和 MyClass2.php 文件.
This example attempts to load the classes MyClass1 and MyClass2 from the files MyClass1.php and MyClass2.php respectively.
<?php
spl_autoload_register(function ($class_name) {
include $class_name . '.php';
});
$obj = new MyClass1();
$obj2 = new MyClass2();
?>
命名空间只是组织类的附加功能.
Namespaces are only an additional feature to organize classes.
正如@IMSoP 在评论中指出的那样, new 并不是唯一一次触发自动加载器的时间.访问类常量,静态方法,或静态属性 也会触发它,运行 class_exists.
As @IMSoP pointed out in the comments, new is not the only time the autoloader is triggered. Accessing a class constant, static method, or static property will also trigger it, as will running class_exists.
这篇关于PHP的“使用"关键字和自动加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!