是否可以在同一个文件中使用同一个命名空间下的多个类

2022-01-14 00:00:00 oop namespaces php psr-4

是否可以在同一个文件中使用同一个命名空间下的多个类?我想做这样的事情:

避免为每个自定义异常类使用一个文件.问题是,当我尝试在另一个类中使用自定义异常之一时,

使用 MyNamespaceHelpersExceptionsCustomException1;

未找到 CustomException1 类.有什么想法吗?

解决方案

我认为这样做在语法上没有任何问题,但我认为没有任何问题 PSR-4 兼容的自动加载器将能够找到不在其自己的专用文件中的类,因为标准是类所属的文件与类本身的名称相同:

<块引用>

  1. 终止类名对应于以.php 结尾的文件名.文件名必须与终止类名的大小写匹配.

因此,如果您想使用这种方法,则必须确保在需要定义这些类时手动include该类文件(基本上,只要您想抛出/捕获任何这些异常).

另一种方法是在另一个类的文件中定义您想要的类,您绝对确定将始终在调用任何 new CustomExceptionN 之前自动加载陈述.您可能会发现,在大多数情况下,记住在使用 Class2 之前首先确保自动加载 Class1 比仅仅遵循标准要麻烦得多并将每个类包含在它自己的文件中,该文件位于正确的命名空间路径中.

Is it possible use multiple classes under the same namespace, in the same file? I want to do something like this:

<?php
  namespace MyNamespaceHelpersExceptions

  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 MyNamespaceHelpersExceptionsCustomException1;

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:

  1. 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.

相关文章