Import a class conditionally using the 'use' keyword

I have never seen this structure anywhere, so I doubt that this is something wrong with an expression like this:

if (condition) { use Symfony\Component\HttpFoundation\Response; } 
+6
source share
2 answers

The only thing that use does is alias the class name. It. Nothing more. Instead of re-writing the full class name in the script:

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

You can shorten this to:

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

Thus, it makes absolutely no sense to want to use use conditionally. It is just a syntax assistant; if it can be used conditionally, your script syntax will become ambiguous, nobody wants something.

This does not reduce the loading of the code, because the code is loaded explicitly only when require / include called or during autoload. The latter is very preferable, because it already lazily goes into action only when necessary.

+8
source

This will result in a syntax error. From TFM:

The use keyword must be declared in the outermost area of ​​the file (global scope) or inside the namespace. This is because imports are performed at compile time, not at run time, so it cannot be block coverage.

+6
source

Source: https://habr.com/ru/post/972757/


All Articles