PHP namespaces and using the \ prefix in declaration

namespaces, php

Solution

As mentioned in the other answers the `namespace` declaration always takes a fully-qualified name and as such a trailing `\` would be redundant and is not allowed.

Writing `namespace \NYTD\ReadingListBackend { ... }` will lead to a proper parse error.

When using the semicolon notation `namespace \NYTD\ReadingListBackend;` on the other hand it is interpreted as `namespace\NYTD\ReadingListBackend;`, which is an access to the constant `NYTD\ReadingListBackend` (the `namespace` keyword here resolves to the currently active namespace, which in your case is the global one).

So your code does not declare any namespace (it is global) and just tries to access a constant. That's why you end up redefining `Exception`.

By the way, the reason why the undefined constant access does not throw a fatal error is class hoisting. Your class declaration is evaluated first, so PHP never actually reaches the constant access (even though it comes first in code).

Problem

The following throws an error stating `Exception` can not be redeclared. ``` namespace \NYTD\ReadingListBackend; class Exception extends \Exception { } ``` However, removing the `\` prefix in the namespace declaration does not: ``` namespace NYTD\ReadingListBackend; ``` I recently adopted PHP namespaces. My understanding is that namespaces prefixed with `\` represent a fully qualified name. So why can't I use the prefix in the namespace declaration? I can when referencing (e.g. `new \NYTD\ReadingListBackend\Exception`). Would appreciate a full explanation as I couldn't find anything in the docs.

Original source