Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP reserved words as namespaces and class names

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 { }
like image 608
Spencer Mark Avatar asked Aug 03 '12 08:08

Spencer Mark


People also ask

What are namespaces in PHP?

PHP Namespaces. Namespaces are qualifiers that solve two different problems: For example, you may have a set of classes which describe an HTML table, such as Table, Row and Cell while also having another set of classes to describe furniture, such as Table, Chair and Bed. Namespaces can be used to organize the classes into two different groups ...

What is an example of a class namespace?

For example, you may have a set of classes which describe an HTML table, such as Table, Row and Cell while also having another set of classes to describe furniture, such as Table, Chair and Bed. Namespaces can be used to organize the classes into two different groups while also preventing the two classes Table and Table from being mixed up.

How do I access classes from outside the namespace?

Any code that follows a namespace declaration is operating inside the namespace, so classes that belong to the namespace can be instantiated without any qualifiers. To access classes from outside a namespace, the class needs to have the namespace attached to it. Use classes from the Html namespace:

How does namespace resolution work in PHP?

Namespace resolution *only* works at declaration time. The compiler fixates all namespace/class references as absolute paths, like creating absolute symlinks. You can't expect relative symlinks, which should be evaluated during access -> during PHP runtime. In other words, namespaces are evaluated like __CLASS__ or self:: at parse-time.


1 Answers

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!

like image 93
Stu Avatar answered Nov 15 '22 07:11

Stu