I have an Exception class:
namespace abc; class AbcException extends Exception { // blah blah }
It produces this error:
Class 'abc\Exception' not found ...
Questions:
What can I do to make this work ?
Useful documents are appreciated.
Thanks for reading my question
The first thing to do is to define a namespace with the namespace keyword at the top of the PHP file. All the code underneath the namespace keyword becomes namespaced code. It's important to note that this keyword must be placed at the top of the file, making sure that nothing precedes it.
Namespaces are qualifiers that solve two different problems: They allow for better organization by grouping classes that work together to perform a task. They allow the same name to be used for more than one class.
Defining multiple namespaces in the same file ¶Multiple namespaces may also be declared in the same file. There are two allowed syntaxes. This syntax is not recommended for combining namespaces into a single file. Instead it is recommended to use the alternate bracketed syntax.
A namespace is a way of grouping identifiers so that they don't clash. Using a class implies that you can create an instance of that class, not true with namespaces. 2. You can use using-declarations with namespaces, and that's not possible with classes unless you derive from them.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With