所以 PHP 7 对命名空间有很好的组使用声明,如下所示:
use Symfony'Component'Console'{
Helper'Table,
Input'ArrayInput,
Input'InputInterface,
Output'NullOutput,
Output'OutputInterface,
Question'Question,
Question'ChoiceQuestion as Choice,
Question'ConfirmationQuestion,
};
但是由于某种原因,相同的语法不适用于单字命名空间(根据手动要求,所有命名空间都来自同一个global
命名空间),如下所示:
use {ArrayAccess, Closure, Countable, IteratorAggregate};
//or
use '{ArrayAccess, Closure, Countable, IteratorAggregate};
两者都会给出错误(而 IDE 没有显示任何语法问题):
PHP Parse error: syntax error, unexpected '{', expecting identifier (T_STRING) or function (T_FUNCTION) or const (T_CONST) or '' (T_NS_SEPARATOR) in ...
多个命名空间的简单标准use
按预期工作:
use ArrayAccess, Closure, Countable, IteratorAggregate; //no errors
那么有什么理由不能在这里应用这样的语法呢?
1)正如"Stefan W"在PHP上写下的评论: 特征 - 手册:
命名空间的"use"始终将其参数视为绝对参数(从全局命名空间开始):
这就是为什么您的示例中没有错误的原因:
use ArrayAccess, Closure, Countable, IteratorAggregate; //no errors
第二部分是,如果我们阅读 PHP 命名空间规范,我们可以看到您使用了以下有效模式:
use namespace-use-clauses ;
或者如果我们阅读"Zend语言解析器",我们可以看到同样的事情:
| T_USE use_declarations ';'
其中T_USE是我们的 PHP 代码中的 "use" 关键字,use_declarations 是 1 个或多个use_declaration元素的列表(基本上是命名空间名称,您将在下面看到),用逗号分隔。
有趣的是,如果我们像这样重写上面的例子:
use 'ArrayAccess, 'Closure, 'Countable, 'IteratorAggregate;
它也会起作用!我们可以在规范中看到这种模式,实际上我们在 Zend 语言解析器中也有这种模式,因为每个 use_declaration 元素都匹配以下模式:
use_declaration:
unprefixed_use_declaration
| T_NS_SEPARATOR unprefixed_use_declaration
;
其中T_NS_SEPARATOR是反斜杠 - "''"。
2)团体使用声明呢?
好吧,如果此示例工作正常:
use Symfony'Component'Console'{Helper'Table, Input'ArrayInput, Input'InputInterface, Output'NullOutput, Output'OutputInterface, Question'Question, Question'ChoiceQuestion as Choice, Question'ConfirmationQuestion};
为什么我们不能写这样的东西?
use {ArrayAccess, Closure, Countable, IteratorAggregate};
//or
use '{ArrayAccess, Closure, Countable, IteratorAggregate};
答:那是因为我们没有匹配规范中的任何有效模式,也没有匹配 Zend 语言解析器中的任何有效模式:
group_use_declaration:
namespace_name T_NS_SEPARATOR '{' unprefixed_use_declarations possible_comma '}'
| T_NS_SEPARATOR namespace_name T_NS_SEPARATOR '{' unprefixed_use_declarations possible_comma '}'
;
没有这样的模式:
'{' unprefixed_use_declarations possible_comma '}'
//or
T_NS_SEPARATOR '{' unprefixed_use_declarations possible_comma '}'
用于组使用声明。