开发者

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


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!


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 good to use "use" when including/extending other class OR libraries.

namespace AbcException;
use Exception;

class AbcException extends Exception {
    // Your Code
}


It's simply a blackslash. Like \Exception.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜