Make your own free website on Tripod.com

Visit the Official PHP Website

Search this Site

PHP Programming

By James N Hitz

Code Re-use

At the beginning of this lesson I promised two lessons - Harvest time. Remember? In the first lesson, we handled date and time manipulation in PHP. In that lesson we learnt how to use getDate(); checkdate(), time(), date() and mktime() functions. In this part, we will learn how to re-use code.

What I mean here by saying code re-use is the ability to use one script more than once. PHP allows you to include code contained in an external file using the include() function.

The include() function copies the contents of an external file and evaluates the contents accordingly. If the included file contains PHP code, the code must be valid and must be escaped - even if the code is the only thing in a file.

To include a file use:

include("fileToInclude");

Let's take an example. Supposing you have the following code in a file called today.php

<table><tr><<td bgcolor="#fafafa"><center>today.php</center></td></tr><tr><td>
<?php
$thisdate = getDate();
print("<b>$thisdate[weekday], $thisdate[mday] $thisdate[month] $thisdate[year]</b>");
?>
</td></tr></table>

This is the code we created in our first encounter with dates. (Come on. It was only a few Epoch Seconds away). Now supposing you want to include this code snippet in all your documents, you would make use of include. In every document, insert this code snippet:

<?php include("today.php"); ?>

If you would like more legibility remember you may also array the code thus:

<?php
	include("today.php");
?>

See?! I am as excited as you are. With this you never will write the same code snippet to do the same time more than once... but there's more.

The included file (today.php in this case) may contain the return; statement to force the code (within today.php) to stop executing and return to the calling program. In PHP4, the return can also "return" a value.

What this means is that the included program can say something to the caller when it finishes executing. Let's take an example.

Virtually, we have a file called validate.php that asks for the user name and password, validates the entered information and returns TRUE or FALSE. The code may look something like this (this is kinda' primitive I must admit):

if(($user == 'James') && ($password =='somepassword')){
	return 1;
} else {
	return 0;
}

If this file is included in another file, a part of the code may be something like this:

$returnValue = include("validate.php");

The ability to have an included file return a value is only possible if you are using PHP version 4 and later.

Always specify the correct full path for the included file. If no path is specified, the attached file is assumed to be in the same path with the calling file.

<< The date() function | More Code Re-use >>

JamHitz Productions