PHP reserved words as namespaces and class names

喜欢而已 提交于 2019-11-27 07:59:04

问题


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 { }

回答1:


PHP will throw an error like:

Parse error: syntax error, unexpected T_ARRAY, expecting T_STRING

if you try:

class Array
{

}
$myClass = new Array;

Instead, try something like

class myArray
{

}
$myClass = new myArray;

[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.

Hope that helps!



来源:https://stackoverflow.com/questions/11792070/php-reserved-words-as-namespaces-and-class-names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!