Is it possible use multiple classes under the same namespace, in the same file(是否可以在同一个文件中使用同一个命名空间下的多个类)
问题描述
是否可以在同一个文件中使用同一个命名空间下的多个类?我想做这样的事情:
避免为每个自定义异常类使用一个文件.问题是,当我尝试在另一个类中使用自定义异常之一时,
使用 MyNamespaceHelpersExceptionsCustomException1;
未找到 CustomException1 类.有什么想法吗?
我认为这样做在语法上没有任何问题,但我认为没有任何问题 PSR-4 兼容的自动加载器将能够找到不在其自己的专用文件中的类,因为标准是类所属的文件与类本身的名称相同:
<块引用>- 终止类名对应于以.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:
- 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.
这篇关于是否可以在同一个文件中使用同一个命名空间下的多个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否可以在同一个文件中使用同一个命名空间下的多个类
基础教程推荐
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 在多维数组中查找最大值 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01