PHP: Require() and Class Hierarchies

2019-03-02 18:35发布

问题:

I'm considering this issue largely a C++/C# programmer, which might help put things into perspective. I haven't been able to find a simple answer to my question, so I apologize if there's one readily available out there. This seems like it'd be a very common issue.

Suppose I have class A, which is a container for instances of class B. class B, in turn, is a container for instances of class C. By container, I mean each class holds an array of certain kinds of objects and a few general parameters describing those objects. Each class is stored in [className].php

Now, I have a script that needs to build an instance of class A. In order to do so, it will need to construct instances of class C. Each set of those will be used to build an instance of class B, and finally, all of the class Bs will be used to build an instance of class A.

The question is, in PHP, where is the best (least-error prone) place to put the require() statements? Some ideas:

  • require() all three classes in the script, and nowhere else
  • require_once() the classes everywhere you need to use them. In this case, you'd require_once() A, B, and C in the script, require B and C in A, and require_once() C in B.
  • require() only the class the next level down in the hierarchy. The script will require(A), A will require(B), and B will require(C). Thus, by requiring A in the script, you get access to all of the classes needed to populate A.
  • Something else, like autoloading.

As always, I appreciate the ideas. While this might be subjective on some level, I do believe some ways may be objectively better than others, and that's what I'm after.

回答1:

I'd go with autoloading. You don't have to worry about where you require_once() your classes if it does it automatically for you. All you have to do is start using the classes you expect to be there, and PHP will call your autoloader to make sure that the classes are loaded.

If you are more used to programming in an environment that has you import things at the top of each file, you might be more comfortable using require_once() at the top of all of your files. I almost prefer this over autoloading because it makes it very clear what each classes dependencies are. However, you get a lot of duplication which you might not enjoy.

Either way works. It is mostly a style choice.



回答2:

Always use require_once to include classes. Always. There is literally no downside. Include the files via require_once in each file they're needed. This cannot fail: You cannot use require_once too many times, and the class is guaranteed to be included and available throughout the entire program.