require() or include() with PHP?

A lot of people mis-use these two functions. In short, the difference is this

  • require() “requires” a file to be “included” before it proceeds, if the “required” file is not found, script execution halts returning a fatal error.
  • include() “includes” a file if it can find it, if not, it returns a warning explaning why (usually just bad file name)

Which one is more important is really up to you, but I would by default recommend using include() over require() just less mess to deal with.

Extending the include functions
PHP added this cute functionality to the include functions called “_once”, so you could include_once() or require_once() a file. They both do the same thing they’ve always done with an exception, they only include a file once. Pretty hard to understand isn’t it? that require_once only requires a file once. Pretty original :) But seriously, this function used to save my life until I realized that it was simply bad design (most of the time) that caused the problems that “_once” functions were created to fix. In other words, If I’m including a file more than once anyways, I need to fix that problem instead of just being lazy and using PHP’s little include_once() speciality function. Now I’m not arguing that they made it, and it ships with PHP so they must still have it in circulation for a reason, yes, you’re correct.

Someone in ##php pointed out to me that although it might come in handy, every time you use include_once or require_once PHP has to look through the list of files already included and check their contents to make sure it hasn’t already included them. (read that again slowly.) Which narrows itself down to a lot of performance wasted because you were too busy to re-design your application a little bit to only include a file once. Think about it, you’re putting the statement there anyways, how hard is it to just make sure you aren’t duplicating it? I posted an article about duping your PHP code here, you should probably read it. It will help you with other things.

In closing, I use include() functions by default and require() if I REALLY need a file. Even then, I just use include(). So, now you know.

Related reading

Leave a Reply