Is it possible use multiple classes under the same namespace, in the same file? I want to do something like this:
<?php
namespace MyNamespace\Helpers\Exceptions
use Exception;
class CustomException1 extends Exception{}
class CustomException2 extends Exception{}
class CustomException3 extends Exception{}
to avoid using one single file for each custom exception class.
The problem is, when I try to use, in another class, one of the custom exceptions,
use MyNamespace\Helpers\Exceptions\CustomException1;
the CustomException1 class is not found. Any ideas?
I don't think there's anything syntactically wrong with doing this, but I don't think any PSR-4 compliant auotloaders will be able to find a class that is not in it's own dedicated file since the standard is that the name of a file a class belongs in is the same as the name of the class itself:
- The terminating class name corresponds to a file name ending in .php. The file name MUST match the case of the terminating class name.
Because of this, if you want to use this approach you will have to ensure to include
that class file manually whenever you will need those classes to be defined (basically, anytime you want to throw / catch any of those exceptions).
An alternative is to define the classes you want to inside of another class' file that you are absolutely certain will always be autoloaded prior to any invocation of any new CustomExceptionN
statements. You will probably find in the majority of cases it is a lot more trouble trying to remember to first be sure to autoload Class1
before using Class2
than it is to just follow the standard and include each class in it's own file located at the proper namespace path.