How PHP Includes Work

Posted on September 6th 2009 6:04pm Sunday, by Blaine

A PHP include allows you to append a file inside of another file. For example, if I had a file called hello-world.php I could attach goodbye-world.php to the end of hello-world.php

hello-world.php

<?php
echo 'Hello World<br>'; // You may know this as print 'Hello World'; they are the same thing.
include('goodbye-world.php');
?>

goodbye-world.php

<?php
echo 'Goodbye World';
?>

Output of hello-world.php when opened with the browser

Hello World<br>
Goodbye World

Now, this works exceptionally well if you are trying to make a basic template system that you can easily edit. If the top of your page (the header) and the bottom of your page (the footer) are the same for each page you only have to edit 1 or 2 files when you are making a change to main layout instead of every page.

The benefits to using a PHP include are simple:

  • Allows you to fix errors faster
  • Removes inconsistencies between pages
  • Allows for faster development

Leave a Reply