Tzu ng
Tzu ng

Reputation: 9244

How to use "root" namespace of php?

I have an Exception class:

namespace abc;

class AbcException extends Exception {
// blah blah
}

It produces this error:

Class 'abc\Exception' not found ...

Questions:

  1. What can I do to make this work ?

  2. Useful documents are appreciated.

Thanks for reading my question

Upvotes: 30

Views: 24204

Answers (5)

cybertig
cybertig

Reputation: 19

Under windows you don't need the leading \ to denote the root namespace. Once you deploy to a *nix environment you will have to explicitly add the \ in front of the class name whenever you use it or put the use statement for each root namespace class you are using before you use them, otherwise you'll get a class not found fatal error.

Upvotes: -1

Suf_Malek
Suf_Malek

Reputation: 666

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

namespace AbcException;
use Exception;

class AbcException extends Exception {
    // Your Code
}

Upvotes: 3

hakre
hakre

Reputation: 198119

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.

Upvotes: 17

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385274

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!

Upvotes: 30

sallaigy
sallaigy

Reputation: 1654

It's simply a blackslash. Like \Exception.

Upvotes: 2

Related Questions