How to use "root" namespace of php?

What can I do to make this work ?

Use a leading backslash to indicate the global namespace:

namespace abc;

class AbcException extends \Exception {
// blah blah
}

Useful documents are appreciated.

There's an entire page devoted to this in the PHP manual!


It's good to use "use" when including/extending other class OR libraries.

namespace AbcException;
use Exception;

class AbcException extends Exception {
    // Your Code
}

The Exception class is resolved to your scripts namespace (PHP Manual) as it starts with:

namespace abc;

You can specifically tell the script which exception to use then:

namespace abc;
use Exception;

class AbcException extends Exception {
// blah blah
}

With this variant you see on top of the file which classes you "import". Additionally you can later on more easily change/alias each Exception class in the file. See also Name resolution rules in the PHP Manual.

Alternatively you can specify the concrete namespace whenever you specify a classname. The root namespace is \, so the fully qualified classname for exception is \Exception:

namespace abc;

class AbcException extends \Exception {
// blah blah
}

This just works ever where, however, it makes your code more bound to concrete classnames which might not be wanted if the codebase grows and you start to refactor your code.


It's simply a blackslash. Like \Exception.

Tags:

Php

Namespaces