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 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 ...
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.
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:
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With