使用关键字"use"有条件地导入类 [英] Import class conditionally with the keyword 'use'

查看:114
本文介绍了使用关键字"use"有条件地导入类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从未在任何地方看到过这种结构,所以我想知道这样的表达式是否存在问题:

I've never seen this structure anywhere, so I wonder if there's something wrong with an expression like this:

if (condition) {

    use Symfony\Component\HttpFoundation\Response;

}

推荐答案

use唯一要做的是 别名 .而已.仅此而已.
不必在脚本中重复编写完全合格的类名:

The only thing use does is to alias a class name. That's it. Nothing more.
Instead of having to repeatedly write the fully qualified classname in your script:

$q = new \Foo\Bar\Baz\Quux;
if ($q instanceof \Foo\Bar\Baz\Quux) ...

您可以将其缩短为:

use Foo\Bar\Baz\Quux;

$q = new Quux;
if ($q instanceof Quux) ...

因此,有条件地使用use绝对没有意义.它只是一个语法辅助工具;如果可以有条件地使用它,则您的 script语法会变得模棱两可,这是没人想要的.

As such, it makes absolutely no sense to want to use use conditionally. It's just a syntactic helper; if it could be used conditionally your script syntax would become ambiguous, which is something nobody wants.

它不会减少代码加载,因为仅通过require/include调用或通过自动加载来显式加载代码.最好选择后者,因为它只有在需要时才懒惰地起作用.

It doesn't reduce code loading, because code is only loaded explicitly by require/include calls or via autoloading. The latter one is greatly preferred, since it already lazily springs into action only when needed.

这篇关于使用关键字"use"有条件地导入类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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