开发者

PHP: require_once and inheritance

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 开发者_JS百科the class controller definition?


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 to include("bla.php") at least one time in the entire run-time of your script. If your previous code:

require_once("bla.php");
class controller{.....}

is in the file controller.php then you can create control_A in the following way:

require_once("controller.php");
class control_A extends controller{...}

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:

/* INSERTED FROM controller.php */
/* INSERTED FROM bla.php */
necessary definitions for controller
/* END bla.php */
class controller{.....}
/* END controller.php */
class control_A extends controller{...}

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 of controller. This isn't just because you required bla.php while declaring it, but also you can't extend a class which hasn't yet been declared. So the following code:

class control_A extends controller{...}

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 in bla.php which must run before defining the class is either unnecessary or can be restructured. What exactly is bla.php doing that you need before defining controller?


As long as you're including the inherited class, it doesn't need requiring again.

I.e.

class1.php:

require_once("tools.php");
class class1 {

}

class2.php:

require_once("class1.php");
class class2 extends class1 {

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜