PHP命名空间问题 [英] PHP Namespace Questions
问题描述
嘿,我是php名称空间的新手,我正在努力使事情变得有意义.我遵循PRO Php MVC e-book
,并且在其中的代码中使用了很多命名空间示例. \Framework\Name
和Framework\Name
之间的区别是什么使我感到困惑?
Hey I am new to php namespaces and I'm trying to make sense of something. I am following the PRO Php MVC e-book
and they use a lot of namespace examples in there code. What's confusing me is the difference between \Framework\Name
and Framework\Name
?
什么时候使用哪个版本,它们之间有什么区别?
When do you use which version and what is the difference between them.
推荐答案
在代码中使用它的地方确实有所不同.
Its really a difference of where its being used in the code.
例如,在use
语句中,可以使用以下任何一种方法:
For example, in a use
statement, either can be used:
<?php
namespace Framework;
use Framework\Name;
// OR
use \Framework\Name;
// Both do the same thing
但是,当您实际在代码中时,如果在名称空间的前面没有\
,则会使代码在文件的当前名称空间中查找.示例:
However, when you are actually in the code, not having the \
in the front of the namespace, will make the code look in the current namespace for the file. Example:
<?php
namespace Framework;
// ...
// The below will actually look for the class `\Framework\Framework\Name`
$class = new Framework\Name();
// However, this will look for, and hopefully find `\Framework\Name`
$class = new \Framework\Name();
这使您可以执行以下操作:在子命名空间上使用use语句,并缩短代码中的调用:示例
This lets you do things like have a use statement on a subnamespace, and shorten your calls in the code: Example
<?php
namespace Framework;
use Framework\Cache;
class test {
public function __construct() {
// Below gets `\Framework\Cache\Memcache`
$memcache = new Cache\Memcache();
// Below gets `\Framework\Cache\Apc`
$apc = new Cache\Apc();
}
}
希望这会有所帮助!
这篇关于PHP命名空间问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!