导入名称空间与包含PHP中的文件 [英] Importing a namespace vs. including files in PHP
问题描述
从PHP 4开始,我开始构建代码库.我已使用require_once
导入类.现在,在PHP 5.3中,我遇到了定义和导入命名空间的问题.
我想将源文件更改为使用导入(use
语句)而不是使用require_once
.我不确定这是正确的决定.
我想这很容易.在类文件的顶部定义名称空间,然后进行搜索和搜索.替换使用它们的其他文件(将require_once
替换为use
).在实践中可能会出什么问题?
性能会有所改善吗?在包含文件时,很明显PHP是如何找到文件的.但是在导入名称空间时,它并不是那么明显.在搜索名称空间并通过PHP对其进行索引时是否会降低性能?
use
和require_once
是完全不同的东西. use
根本不执行任何文件导入. use
只是让您的生活更轻松.不必每次都写Full\Path\To\Class
,而是可以做到
use Full\Path\To\Class
$bar = new Class();
您仍然有责任提供正确的文件.
您可以依靠 PHP自动类,而不是手工加载所有文件.正在加载.
您可以使用作曲家或类似 Zend2 ,它们会为您处理所有自动加载的内容.>
迁移现有代码以使用自动加载和use
语句而不是include_once
可能会非常耗时.很可能没有搜索和替换解决方案.
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?
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.
这篇关于导入名称空间与包含PHP中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!