PHP:require_once 和继承
如果我有:
require_once("bla.php");
class controller{.....}
如果我随后在不同的文件中创建 class control_A extends controller{...}
,我是否需要再次说 require_once("bla.php");
,还是遗传的?
如果 require_once
是在 类控制器
定义中完成的怎么办?
If I have:
require_once("bla.php");
class controller{.....}
If I then create in a different file class control_A extends controller{...}
, do I need to again say require_once("bla.php");
, or is it inherited?
What if the require_once
is done inside the class controller
definition?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
到目前为止,我们有两个相互矛盾但同样正确的答案 =) 让我们看看我是否不能将两者结合成一个更具体的总答案。
如果任何类需要
bla.php
中的任何代码或定义,那么您将需要在整个运行时至少一次include("bla.php")
你的脚本。如果您之前的代码:在文件
controller.php
中,那么您可以通过以下方式创建control_A
:这是因为
require_once()
函数本质上是将文件的内容复制并粘贴到脚本中的该行。因此,上面的内容将与此等效:如您所见,只需要求
controller.php
,现在就可以看到并解析控制器的必要定义。您不能做的是省略控制器
的声明。这不仅是因为您在声明时需要bla.php
,而且您无法扩展尚未声明的类。因此,以下代码:会给您一个错误,因为控制器尚未定义。
然而,需要考虑一件事 - 由于类
controller
不扩展任何其他类,因此它不应该有任何外部依赖项。很有可能,无论您在定义类之前必须运行的bla.php
中执行的操作,要么是不必要的,要么是可以重构的。在定义controller
之前,bla.php
到底需要做什么?So far we have two contradicting, but equally correct answers =) Let's see if I can't combine the two into a more specific total answer.
If any class requires any code or definitions in
bla.php
, then you will need toinclude("bla.php")
at least one time in the entire run-time of your script. If your previous code:is in the file
controller.php
then you can createcontrol_A
in the following way:This is because the
require_once()
function essentially copies and pastes the contents of the file into the script at that line. Therefore the above will be seen equivalent to this:As you can see, just by requiring
controller.php
, the necessary definitions for controller are now seen and parsed. What you can not do is omit the declaration ofcontroller
. This isn't just because you requiredbla.php
while declaring it, but also you can't extend a class which hasn't yet been declared. So the following code:will give you an error since controller hasn't been defined.
One thing to consider, however- since the class
controller
doesn't extend any other class, it should not have any external dependencies. There's a good chance that whatever you do inbla.php
which must run before defining the class is either unnecessary or can be restructured. What exactly isbla.php
doing that you need before definingcontroller
?只要您包含继承的类,就不需要再次要求。
即
class1.php:
class2.php:
As long as you're including the inherited class, it doesn't need requiring again.
I.e.
class1.php:
class2.php: