PHP/MySQL : Functions and libraries
Jean-Guillaume Birot
Creating a Reusable Library
Now let's imagine that we want to apply the
writeMessage function to all the pages of the site. For this, PHP also provides us with a mechanism: include files. This is a feature common
to certain Web servers and known as Server Side Include (SSI). It is, however, more flexible in PHP.
We are going to create a library file called
maFonction.php, which contains only the function source code:
1: <?php
2:
3: /*
4: File maFonction.php
5: Useful functions library
6: Author: J.G.Birot
7: */
8:
9: /* HTML message formatting function */
10: function writeMessage ($text)
11: {
12: $html = "<H1 align='center'>".$text."</H1>";
13: print($html); // Display
14: }
15:
16: ?>
In the initial hello.php file, we will replace the function definition with the following line:
include("maFonction.php"); // utility library
This
include function enables you to copy the contents of the file whose URL is passed as an argument, into the page. We just need to insert
this line in all the pages that make use of our personal functions library.
Not only will you find on the Web free downloadable functions libraries that can be included in your pages, but you will also
be able to use them to share simple HTML code between several pages. An increasing number of professional sites are giving
preference to this methodology over frames, which are more difficult to control. It is common to see a site header, a menu,
or a footer included in this fashion. Of course, all this remains invisible to the user.
The result is exactly the same as the one in the previous page.
Comment your code. On lines 3 to 7, 9 and 13, you can see so-called
comments. Do not hesitate to make use of them, because they will remind you later on what you intended to do with the code. In PHP,
you can write a comment that spans several lines by starting it with
/* and terminating it with
*/ (lines 3 to 7 and 9), or one that is located at the end of a line by starting it with a double slash
// (line 13).