6

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 { }
Spencer Mark
  • 5,263
  • 9
  • 29
  • 58

1 Answers1

10

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!

Stu
  • 4,160
  • 24
  • 43
  • Thanks Stu - that's what I thought, but couldn't really test it properly with my framework as at the moment there are plenty of the problems there while I'm converting everything. – Spencer Mark Aug 03 '12 at 08:47
  • I've used class Object before without issue though I only extended it never actually created directly. – gunnx Aug 03 '12 at 08:49
  • @gunnx, that's interesting... I've not tried it before, but I suppose because you're not calling it explicitly it's not going through the same route as it would by calling the class from the php itself, that may have been why it went through. Although I wouldn't recommend using reserved names at all just in case you need to extend you app in the future, you can never call that class and renaming it would be a pain to iterate that through the whole app. – Stu Aug 03 '12 at 09:13
  • No, it seems Object isn't a reserved word, my bad! `new String` throws an error but `new Object` doesn't as it's not in the reserved keywords list: http://www.php.net/manual/en/reserved.keywords.php – Stu Aug 03 '12 at 09:16
  • Yeah I've decided to use Entity as my base class instead of Object in my new project. Array definitely doesnt work :) – gunnx Aug 03 '12 at 09:16