Import class conditionally with the keyword 'use'

我的未来我决定 提交于 2019-12-22 05:49:10

问题


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;

}

回答1:


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) ...

You can shorten that to:

use Foo\Bar\Baz\Quux;

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

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.

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.




回答2:


This will throw a syntax error. From TFM:

The use keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations. This is because the importing is done at compile time and not runtime, so it cannot be block scoped.



来源:https://stackoverflow.com/questions/24929294/import-class-conditionally-with-the-keyword-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!