问题描述
最近我已经开始将我的框架转换为使用php名称空间,而我似乎找不到答案的一个问题是-使用"Object","Array"等保留字是否合法? ,字符串"作为名称空间以及该名称空间中的类名称?一个例子是:
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 System\Object;
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保留字作为名称空间和类名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!