PHP:Require()和类层次结构 [英] PHP: Require() and Class Hierarchies

查看:206
本文介绍了PHP:Require()和类层次结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我主要在考虑这个问题,这是一个C ++/C#程序员,这可能有助于将其视为现实.我无法找到问题的简单答案,因此,我很抱歉是否有一个简单的答案.这似乎是一个非常普遍的问题.

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.

假设我有 A类,它是 B类的实例的容器.反过来, B类 C类实例的容器.通过容器,我的意思是每个类都包含某些种类的对象的数组以及描述这些对象的一些常规参数.每个类都存储在[className] .php

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

现在,我有一个脚本,它需要构建类A的实例.为此,它将需要构造类C的实例.每组实例都将用于构建类B的实例,最后,所有的B类将用于构建A类的实例.

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.

问题是,在PHP中,放置require()语句的最佳位置(最容易出错)在哪里?一些想法:

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

  • require()脚本中的所有三个类,仅此而已
  • require_once()随处都可以使用它们的类.在这种情况下,您需要脚本中的require_once()A,B和C,在A中需要B和C,在B中需要require_once()C.
  • require()仅在层次结构中向下一级的类.该脚本将需要(A),A将需要(B),B将需要(C).因此,通过在脚本中要求A,您可以访问填充A所需的所有类.
  • 还有其他东西,例如自动加载.

一如既往,我很欣赏这些想法.尽管这在某种程度上可能是主观的,但我确实相信某些方法可能在客观上比其他方法更好,而这就是我所追求的.

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.

推荐答案

我会自动加载.如果require_once()自动为您上课,您不必担心.您要做的就是开始使用您期望的类,PHP将调用您的自动加载器以确保已加载这些类.

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.

如果您更习惯于在每个文件的顶部导入内容的环境中进行编程,则在所有文件的顶部使用require_once()可能会更自在.与自动加载相比,我几乎更喜欢此方法,因为它可以很清楚地知道每个类的依赖关系.但是,您会得到很多您可能不喜欢的重复内容.

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.

这篇关于PHP:Require()和类层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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