Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

php - Import class conditionally with the keyword 'use'

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

if (condition) {

    use SymfonyComponentHttpFoundationResponse;

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 FooBarBazQuux;
if ($q instanceof FooBarBazQuux) ...

You can shorten that to:

use FooBarBazQuux;

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...