Include vs require

As the website you just started expands to have more than one page and a decent number of lines of code you will start feeling a tingling sensation on your finger tips. At first, you won’t know what it is. But as your website sprouts more and more pages and the number of lines of code in a page goes from double to triple digits and beyond you’ll slowly grow to understand this overwhelming feeling you’ll have: the urge to reuse code!

To be able to reuse the same code in different pages you need to bring on a very powerful weapon PHP has to offer: file inclusion. For this you have four very similar directives:

  • include
  • include_once
  • require
  • require_once

These statements includes and evaluates the specified file during the execution of the script.
The syntax to use them is:

1
2
include 'path_to_file/file.ext';
require 'path_to_file/file.ext';

or

1
2
include ('path_to_file/file.ext');
require ('path_to_file/file.ext');

If no path is given the default path is the one set through include_path configuration directive in php.ini file.

Include_once and require_once perform an additional check: if the file has already been included it will not be included again, so only use them when you need such behavior (for example when including function declarations).

Include and require are similar except the way they handle errors: include yields an warning and lets the script continue running whereas require halts the script with a fatal error. That is why include is better suited for files that hold non-essential information for the execution of the script, information it can go without. Require is usually used when you include mandatory information, code that would cause your script to stop working or worse, working incorrectly: functions and variable declarations, database connection, configuration files, security etc.

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Categories

Archives

Calendar

February 2012
M T W T F S S
« May    
 12345
6789101112
13141516171819
20212223242526
272829