How to use “root” namespace of php?

房东的猫 提交于 2019-12-17 09:33:14

问题


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


回答1:


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!




回答2:


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.




回答3:


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

namespace AbcException;
use Exception;

class AbcException extends Exception {
    // Your Code
}



回答4:


It's simply a blackslash. Like \Exception.



来源:https://stackoverflow.com/questions/6593621/how-to-use-root-namespace-of-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!