Thursday, March 31, 2011

thank you Jesper Jarlskov this What is PHP include is very helpful

What is PHP include

According to the PHP manual:
The include() statement includes and evaluates the specified file.
In human readable form this means that everytime you include() a file in your PHP-code the following will happen:
  1. PHP reads the included file
  2. Any code outside classes and functions will be executed
  3. All classes and methods is made available for later use
  4. Code execution continues from the next line after your include()-call
If your included file only contains PHP-code without any functions or classes, the code will be executed procedurally, the same way code in a function is executed everytime you call a function.

How to PHP include

A great use of the PHP include function is to spread different parts of your page into different files, allowing you to include the parts you need, whenever you need them, allowing code reuse. So instead of creating complete pages all the time, stuff that you need in several pages can be put into files of their own, so they can be used several times, just like you can apply the same CSS-stylesheet to several pages.
An example could be the header of your files. All of your pages needs a header with opening html and head tags and so on. This will very often be the same header for all of your pages. This makes the header a good thing to move into an external file, that can be included when you need it. The same goes for a footer. This means everytime you want to serve a page to a user you can do three include:

include('header.php');
include('content.php');
include('footer.php');

This allows you to change the content, depending on which page on your web site the user is looking for.
The header could then contain something like:

<html>
<head>
<title>Full page!</title>
</head>
<body>
W00h00 header ftw!
<div id="main menu"><a href="index.php">frontpage</a>

and the footer could be something like:

W00h00, footer ftw!
</body>
</html>

This will provide the full skeleton needed to glue together a validating page. Between the header and footer you are then able to include whatever content you’d like to serve to your users. The important thing here is that your included content should only output html that you would normally put between the <body> and </body> tags of your page. If your include(‘content.php’); outputs a fully validating web page, the combination of the three include will together output a web page embedded into another web page. This is NOT valid HTML.
I hope this makes sense, and provides a bit of clarity of how the PHP include() could be used (this is not the only use of this powerful method). If you’ve got any questions to this subject, feel free to ask them in the comments, and I will do my best to answer them :-)

1 comment:

  1. I'm glad it helped you. It's a very powerful function that can save you a lot of work, and make you code a lot more readable :-)

    ReplyDelete