Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

php - Is it possible use multiple classes under the same namespace, in the same file

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...