Does PHP's use statement cause extra work when loading classes?

旧巷老猫 提交于 2019-12-23 13:57:07

问题


Code Sample 1

use Outline\Drawing;
$var = new Drawing();

Code Sample 2

$var = new Outline\Drawing();

Question:

Does PHP make hardware work harder (look up more files or do more processing) if I use code in sample 1? I am sure something gets done, even if it is at the level of some code that figures out which use line gets matched up with which class. I want to find out exactly what is happenning.

In short:

  • What does PHP do when working out the connection between the use of the use statement and a class it is supposed to be for?
  • Are PSR-0/PSR-4 autoloaders affected in the way they work when it comes to these two code samples?

回答1:


What does PHP do when working out the connection between the use of the use statement and a class it is supposed to be for?

The use statement doesn't actually load the namespace/class into your file. It simply sets up a list of aliases to refer to the classes in that namespace.

When it encounters a class that hasn't yet been declared, it uses that list of aliases to try to fully qualify the class name (prefix replacement). If it can't find an alias for the class, it'll use the namespace of the current scope to qualify the class name.

Only when the class name is fully qualified, that php will try to autoload the class (calling the various autoloaders that might have been defined).

Are PSR-0/PSR-4 autoloaders affected in the way they work when it comes to these two code samples?

No, autoloaders are not affected in the way they work by the difference in your code samples because php will call the autoloaders exactly the same way with exactly the same parameters.



来源:https://stackoverflow.com/questions/22507303/does-phps-use-statement-cause-extra-work-when-loading-classes

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