Importing a namespace vs. including files in PHP

情到浓时终转凉″ 提交于 2020-01-01 08:53:38

问题


I have started building my code library since PHP 4. I have used require_once to import classes. Now with PHP 5.3 I have met defining namespaces and importing them.

I would like to change my source files to use importing (use statement) instead of using require_once. Is this the right decision, I am not sure.

I guess it would be easy. Defining namespace at the top of class files and doing a search & replace on other files that use them (replace require_once with use). On practice what may go wrong?

And will there be performance improvement? On including file it is obvious how PHP finds the file. But on importing namespaces it is not that obvious. Is there a performance loss on searching namespaces and indexing them by PHP?


回答1:


use and require_once are completely different things. use is not doing any file importing at all. use is just making your life easier. Instead of writing Full\Path\To\Class every time, you can do

use Full\Path\To\Class

$bar = new Class();

Your are still responsible to include the right files.

Instead of loading all the files by hand, you could rely on PHP auto class loading.

You can use Composer or Frameworks like Symfony 2 or Zend2 which are handling all the autoloading stuff for you.

Migrating existing code to use autoloading and use statements instead of include_once may be very time consuming. There's most likely no search and replace solution.



来源:https://stackoverflow.com/questions/15434366/importing-a-namespace-vs-including-files-in-php

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