include, require, include_once or require_once

Well the question Today is which is the best or correct one to use?

There are a few reasons to choose between include and require I suppose, based on the importance of the file you are 'including'.  If I was including a config or settings files with critical information in it, or a bootstrap loader file which all my files need, I'd be inclined to use require over include - as the file is Required, and not an optional file that the site can load without.  Take on the other hand if I was pulling in a file with some adverts on it, or a banner on the site from another template file, I'd be more inclined to use include, as this isn't mission critical to the site loading - Ok I'd really like it there, but if there is an issue for whatever reason, I still want the rest of the page to continue loading.

Next comes the question of include/require vs include_once/require_once.
I guess the age old discussion of performance comes to mind, if I know for a fact (and I should It's my project), that the file I'm pulling in is only to be read in once, even still I shouldn't have to use *_once statements, however if for whatever reason I decide I do, as far as I'm aware, the process of calling:

require_once 'require_me.inc.php';

The system is going to go:

  • Ok, we require this file 'require_me.inc.php'
  • has it been required already? Let's check..
  • [check previous list of required files in this execution]
  • if it has been, don't include it again
  • [continue script]
If I choose to just require it:

require 'require_me.inc.php';

The system should go:

  1. Ok we require this file 'require_me.inc.php'
  2. pull it in now
  3. [continue script]
OK, now that process takes microseconds (if not faster), on server set ups these days, but scale this up to a situation where you may have mega numbers of files included, is this going to cause performance issues?  I'm not sure, would be interesting to benchmark the exact differences in performance of the commands, and I might in fact do that someday - just not today.

If anyone is prepared to benchmark these statements for me, it would be interested to see.

Also, you may have noticed that the code snippets above I used require 'file.php'; as opposed to require('file.php');  This is because I believe include and require are statements as opposed to methods which one passes variables into.   in the same way I'd call new MyClass(); as opposed to new(MyClass());

Thanks for reading.

Comments

Popular posts from this blog

Navigating the Jungle of Web Traffic: A Technical Team Lead's Guide to "I'm a Celebrity, Get Me Out of Here"

TCP Handshake over IPv6

The Vital Importance of Secure Wi-Fi Networks