是否可以在同一文件中的同一名称空间下使用多个类 [英] Is it possible use multiple classes under the same namespace, in the same file

查看:92
本文介绍了是否可以在同一文件中的同一名称空间下使用多个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;

找不到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:

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

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

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

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

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.

这篇关于是否可以在同一文件中的同一名称空间下使用多个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆