问题描述
最近我开始将我的框架转换为使用 php 命名空间,但我似乎找不到答案的一个问题是 - 使用保留字如对象"、数组"是否合法", 'String' 作为该命名空间内的命名空间和类名?一个例子是:
Recently I've started converting my framework to use the php namespaces and one question to which I can't seem to find the answer is - is it 'legal' to use reserved words such as 'Object', 'Array', 'String' as namespace and class name within that namespace? An example would be:
namespace SystemObject;
class String { }
class Array { }
推荐答案
PHP 会抛出如下错误:
PHP will throw an error like:
Parse error: syntax error, unexpected T_ARRAY, expecting T_STRING
如果你尝试:
class Array
{
}
$myClass = new Array;
相反,尝试类似
class myArray
{
}
$myClass = new myArray;
[edit] 我会详细说明一下,它们被保留是有原因的,因为在上面的第一个场景中,PHP 无法区分你定义一个数组或初始化一个类同名,所以会报错.没有办法像在 MySQL 中那样解决这个问题,例如,您可以使用反引号来转义保留字.所以在 PHP 中你不得不改变名字,你不必改变太多,只要你不使用与保留字完全相同的名字,一个字符就可以了.
[edit] I'll elaborate on that a little, they're reserved for a reason because in the first scenario above, PHP wouldn't be able to tell the difference between you defining an array or initialising a class of the same name, so it throws an error. There's no way round this like in MySQL, for example, where you can escape reserved words with a backtick. So in PHP you're forced to change the name, you don't have to change it much, one char will do as long as you're not using the exact same name as a reserved word.
希望有帮助!
这篇关于PHP 保留字作为命名空间和类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!