PHP Chapter 8 (Create your own Functions)

You've been working with string functions in the last section, and references to functions have been made in other sections. But what is a function, and how do you create them? In this section, you'll find out.

What is a Function?

A function is just a segment of code, separate from the rest of your code. You separate it because it's nice and handy, and you want to use it not once but over and over. It's a chunk of code that you think is useful, and want to use again. Functions save you from writing the code over and over. Here's an example.
Suppose you need to check text from a textbox. You want to trim any blank spaces from the left and right of the text that the user entered. So if they entered this:
" Bill Gates "
You want to turn it into this:
"Bill Gates"
But you also want to check if the user entered any text at all. You don't want the textbox to be completely blank!
You can use the PHP inbuilt function called trim( ). Like this:
$user_text = trim( $_POST['text1'] );
That will get rid of the white space in the text box. But it won't check if the text box is blank. You can add an if statement for that:
if ($user_text == "") {
error_message = "Blank textbox detected";
}
But what if you have lots of textboxes on your form? You'd have to have lots of if statements, and check each single variable for a blank string. That's a lot of code to write!
Rather than do that, you can create a single function, with one if statement that can be used for each blank string you need to check. Using a function means there's less code for you to write. And it's more efficient. We'll see how to write a function for the above scenario in a moment. But first, here's the basic syntax for a function.
function function_name() {
}
So you start by typing the word function. You then need to come up with a name for your function. You can call almost anything you like. It's just like a variable name. Next, you type two round brackets ( ). Finally, you need the two curly brackets as well { }. Whatever you function does goes between the curly brackets. Here's a simple example that just print something out:
function display_error_message() {
print "Error Detetceted";
}
In the example above, we've started with function. We've then called this particular functiondisplay_error_message. In between the curly brackets, there a print statement. Try it out with this script:
<?PHP
function display_error_message( ) {
print "Error Detetceted";
}
?>
Run your script and see what happens. You should find that nothing happens!
The reason that nothing happened is because a function is a separate piece of code. It doesn't run until you tell it to. Just loading the script won't work. It's like those inbuilt functions you used, such as trim. You can't use trim( ) unless you type out the name, and what you want PHP to trim. The same applies to your own functions – you have to "tell" PHP that you want to use a function that you wrote. You do this by simply typing out the name of your function. This is known as "calling" a function. Try this new version of the script.
<?PHP
function display_error_message() {
print "Error Detetceted";
}
display_error_message( );
?>
After the function, we've typed out the name again. This is enough to tell PHP to run our code segment. Now change your code to this, and see what happens:
<?PHP
display_error_message();
function display_error_message() {
print "Error Detetceted";
}
?>
If you have PHP 4 or above, you should see no difference – the function will still get executed with the name above or below the function. But for neatness and readability's sake, it's better to put all of your function either at the top or bottom of your scripts. Or better yet, in a separate PHP file. You can then use another inbuilt function called "Include" (which we'll get to soon)

PHP Variable Scope

There's a thing called scope in programming. This refers to where in your scripts a variable can be seen. If a variable can bee seen from anywhere, it's said to have global scope. In PHP, variables inside of functions can't be seen from outside of the function. And functions can't see variables if they are not part of the function itself. Try this variation of our script as an example:
<?PHP
$error_text = "Error Detetceted";
display_error_message();
function display_error_message( ) {
print $error_text;
}
?>
This time, we have set up a variable called $error_text to hold the text of our error message. This is set up outside of the function. Run the script, and you'll get a PHP error message about " Undefined variable".
Likewise, try this script:
<?PHP
display_error_message();
print $error_text;
function display_error_message() {
$error_text = "Error message";
}
?>
This time, the variable is inside the function, but we're trying to print it from outside the function. You still get an error message. Here's a correct version:
<?PHP
display_error_message();
function display_error_message() {
$error_text = "Error message";
print $error_text;
}
?>
Here, we have both the variable and the print statement set up inside of the function. The error message now prints.
So if you need to examine what is inside of a variable, you need a way to get the variable to the function. That's where arguments come in.

PHP Functions and Arguments

In the upper two sections, you saw how to set up your own functions, and the importance of Scope. In particular, you learnt that you need a handy way to pass values to your function. That's where arguments come in.

Arguments

Functions can be handed variables, so that you can do something with what's inside of them. You pass the variable over to your functions by typing them inside of the round brackets of the function name. Here's a script similar to the one you saw earlier:
<?PHP
$error_text = "Error message";
display_error_message($error_text);
function display_error_message($error_text) {
print $error_text;
}
?>
The only difference is the that we now have something between the round brackets of our function:
function display_error_message($error_text) {
}
The name is the same, but we've put a variable in between the round brackets. This is the variable that we want to do something with. The one called $error_text. By typing a variable inside of the round brackets, you are setting up something called an argument. An argument is a variable or value that you want your function to deal with.
Notice how the function is called:
$error_text = "Error message";
display_error_message($error_text);
The first line puts something into the variable. But when you want to hand something to a function that has an argument, you need to type it between the round brackets of the function call. In our script, we're typing the name of the variable. But this would do just as well:
display_error_message("Error message");
Here, we're putting direct text between the round brackets. That works ok. But try it like this:
$error_text = "Error message";
display_error_message( );
You'll get an error message from PHP. Something like this:
"Warning: Missing argument 1 for display_error_message( )"
That's telling you that your function has been set up to take an argument, but that you've left the round brackets empty when you tried to call the function.
Your functions can have more than 1 argument. Just separate each argument with a comma. Like this:
function error_check($error_text, error_flag) {
}
To call this function, you'd then need to hand it two arguments:
$error_text = "Error message";
error_flag = 1;
error_check($error_text, error_flag);
If you only hand the above function 1 argument, you'd get error messages from PHP.
So, to recap:
  • To pass something to a function, create an argument
  • To call a function that has an argument, don't leave the round brackets empty
In the next part, you'll see a function that checks for blank text boxes. The function has 1 argument.

Check for blank Textboxes with PHP

If you remember the script that we wanted to create earlier it was this:
  1. Get the text that a user entered in a textbox on a form
  2. Trim any blank spaces from the left and right of the text
  3. Check that what you have left is not a blank string
So we want to check that the textbox doesn't just contain this "". There has to be something in it, like "Bill Gates". Here's a script that does all three items on our list:
<?PHP
$user_text = trim("Bill Gates");
display_error_message($user_text);
function display_error_message($user_text) {
if ($user_text == "") {
print "Blank text box detected";
}
else {
print "Text OK";
}
}
?>
Try it out. When you run the script, you should find that Text OK prints. Now change this line:
$user_text = trim("Bill Gates");
to this:
$user_text = trim("");
Run your script again. This time, Blank text box detected should print out. Obviously, we're not getting the text from a textbox on a form, but just simulating the process. If you want to try out a version with all the HTML, here it is. This next script checks two textboxes on a form.
Try the script out. But the point is, that we're using the same function to check for blank text boxes. We're not writing the same code over and over. Just call our one function as and when needed.
In the next part, we'll see how to get values back out of functions.

Getting values out of PHP functions

When you're creating your own functions, you may notice that they can be broken down in to two categories: functions that you can leave, and just let them do their jobs; and functions where you need to get an answer back. As an example, here's the two different categories in action:
print ("Get on with it!");
$string_length = strlen($string_length);
The print function is an example of a function that you can leave, and just let it do its job. You just tell it what to print and it gets on with it for you. But a function like strlen( ) is not. You need something back from it – the length of the string.
Suppose you had a function that worked out a 10 percent discount. But you only want to apply the discount if the customer spent over 100 pounds. You could create a function that is handed the amount spent. Then check to see if it's over a 100 pounds. If it is, the function calculates the discount; if not, don't apply the discount. But in both cases, you want the function to return the answer to your question – What do I charge this customer? Here's the script:
<?PHP
$total_spent = 120;
$order_total = calculate_total($total_spent);
print $order_total;
function calculate_total($total_spent) {
$discount = 0.1;
if ($total_spent > 100) {
$discount_total = $total_spent - ($total_spent * $discount);
$total_charged = $discount_total;
}
else {
$total_charged = $total_spent;
}
return $total_charged;
}
?>
The lines to concentrate on are the ones for the $total_spent variable. The code first sets up a total amount spent, which in practice may come from a form on a text box, or a hidden field:
$total_spent = 120;
The next line is our function call:
$order_total = calculate_total($total_spent);
The function call is now on the right of the equals sign ( = ). To the left of the equals sign is just a normal variable - $order_total . If you're setting up your function like this then you are asking PHP to return a value from your functions, and put the answer into a variable on the left of the equals sign. PHP will go off and calculate your function. When it's found an answer, it will try to return a value. The answer will be stored in the name of your function, calculate_total( ) for us. But look at the function itself, and the line at the end:
function calculate_total($total_spent) {
$discount = 0.1;
if ($total_spent > 100) {
$discount_total = $total_spent - ($total_spent * $discount);
$total_charged = $discount_total;
}
else {
$total_charged = $total_spent;
}
return $total_charged;
}
The last line is:
return $total_charged;
The return word tells PHP to return a value. The value it returns is whatever you have stored in the variable that comes after the word return. Here, were telling PHP to set the answer to the function called calculate_total( ) to whatever is stored in the variable we've called $total_charged. It's this that will get stored in our variable called $order_total.
If you're finding this a bit tricky, remember what a function is: a separate piece of code that does some work for you. It can either return a value, or not return a value. It depends entirely on your needs. But don't worry about the majority of the code above – just concentrate on the coloured parts.
In the script above, you'd want to get something back from the function, rather than letting it just print something out. If you ran the previous script, you'll notice that the function prints out the same thing twice. To stop that happening, we can get a return value, and put it in a variable. We can then check what is coming back from the function, to check what's in it.

By Ref, By Val

Functions can be quite hard to get used, if you've never met them before. Another difficult part to understand is how values can change, or not change, depending on scope. Scope, if you recall, refers to where in your code a variable can be seen. If you just do this, for example:
$Variable_Value = 10;
example( );
function example() {
print $Variable_Value;
}
then you'll get a PHP error about "undefined variable". That's because the function called example( ) can't see what's inside of the variable called $Variable_Value.
In order for the function to be able to see what’s inside of the variable called $Variable_Value, you can set up the function to accept an argument. You'd then type the variable name between the round brackets, when you come to call it. Like this:
<?PHP
$Variable_Value = 10;
example($Variable_Value);
function example($Variable_Value) {
print $Variable_Value;
}
?>
If you run the code above, it now prints out the number ten. But it's important to bear in mind that you are just handing the function a copy of the variable. You're not effecting the original. As an example, change your code to this:
<?PHP
$Variable_Value = 10;
print "Before the function call = " . $Variable_Value . "<BR>";
example($Variable_Value);
print "After the function call = " . $Variable_Value;
function example($Variable_Value) {
$Variable_Value = $Variable_Value + 10;
print "Inside of the function = " . $Variable_Value . "<BR>";
}
?>
Here, we have three print statement: one before the call to the function, one inside of the function, and one after the function call. But we're printing out the value of the variable called $Variable_Value each time. Inside of the function, we're adding ten to the value of the variable. When you run the code, it will print out this:
Before the function call = 10
Inside of the function = 20
After the function call = 10
The important one is After the function call. Even though we changed the value of $Variable_Value inside of the function, it still print 10 after the function call! That's because the function was handed a copy, and NOT the original.
When you hand a function a copy of a variable, it's called passing the variable by value (just a copy). The alternative is to NOT pass a copy, but to refer back to the original. Make one small change to your script. This:
function example(&$Variable_Value) {
The only addition is a & character before the variable between round brackets. This tells PHP that you want to make changes to the original, and don't just want a copy. When you run the script, it now print out the following:
Before the function call = 10
Inside of the function = 20
After the function call = 20
After the function call, we now have a value of 20! So a change to the value of the variable outside the function has been made. When you makes changes to the original like this, it's called passing the variable by reference (don't just copy it – remember it).
Try not to worry about value and reference. Unless the answers you're getting back from your function are rather odd, that is!

PHP Server Variables

PHP stores a list of information about the server. This will include things like, the browser the visitor is using, the IP address, and which web page the visitor came from. Here's a script to try with those three Server Variables:
$referrer = $_SERVER['HTTP_REFERER'];
$browser = $_SERVER['HTTP_USER_AGENT'];
$ipAddress = $_SERVER['REMOTE_ADDR'];
print "Referrer = " . $referrer . "<BR>";
print "Browser = " . $browser . "<BR>";
print "IP Adress = " . $ipAddress;
These are useful if you want to log your stats, or to ban a particular IP address! (If you run the script on a local machine, you may get an error for the referrer.)
So to get at the values in Server Variables, the syntax is this:
$_SERVER['Server_Variable']
You start with a dollar sign, then an underscore character ( $_ ). Then you add the word SERVER. In between square brackets, you type the name of the server variable you want to access. Surround this with either single or double quotes.
Because you are returning a value, you need to put all that on the right hand side of an equals sign. On the left of the equals sign ( = ), you need a variable to hold the string that is returned.
The server variables are held in an array (associative), so you can use a foreach loop to get a list of all available ones. Try this script:
<?PHP
foreach($_SERVER as $key_name => $key_value) {
print $key_name . " = " . $key_value . "<br>";
}
?>
What the script does is to loop round all the server variables and print out the keys and values in the SERVER array.

PHP Header Function

When you request a web page be brought back to your browser, you're not just bringing back the web page. You're also bringing back something called a HTTP HEADER. This is some extra information, such as type of programme making the request, date requested, should it be displayed as a HTML document, how long the document is, and a lot more besides.
One of the things HTTP HEADER also does is to give status information. This could be whether the page was found (404 errors), and the location of the document. If you want to redirect your users to another page, here's an example:
<?PHP
header("Location: http://www.homeandlearn.co.uk/");
?>
<html>
<body>
</body>
</html>
Note how the header code goes before any HTML. If you put header code after the HTML, you'll get an error along the lines of "Cannot modify header information."

The PHP INCLUDE Function

Being able to include other files into your HTML code, or for your PHP scripts, is a useful thing. The include( ) function allows you do this.
Suppose you have a text file that you want to include in a web page that you've already got up and running. You could copy and paste the text from the file straight into you HTML. Or you could use the include( ) function
As an example for you to try, there are two files amongst the ones you downloaded (in the scripts folder), called include.php and textfile.txt. Load up the one called include.php.
Now take a look at the code for this page:
<HTML>
<HEAD>
<TITLE>Include files</TITLE>
</HEAD>
<BODY>
<H3>Normal text here </H3>
Normal text written in a HTML Editor
<H3>Include File here</H3>
<?PHP include "textfile.txt" ; ?>
</BODY>
</HTML>
Our PHP code is in red. Here it is:
<?PHP
include "textfile.txt";
?>
So in between PHP script tags, type the word include. After the word include, type the name of the file you want to include on your page. Your filename can either go after a space, and between quotation marks, or you can put it in round brackets (again, with the quotes).
As well as including text, you can include HTML. This can save you lots of work. For example, a web page typically contains a menu bar, with links to other areas of your site. Something like this:
A Menu Bar
Suppose you decide to add a new section to your site. The new page should be like this:
A new section added to the menu bar
If your site contains lots of pages, that would mean having to amend the HTML of all of them. A painful and dreaded task! Instead, use the include( ) function.
To see how it works, load up the page called links.php that is among the files you downloaded (in the scripts folder): you should see the first menu bar. This has the include line, that points to another file - linksPage.txt (this is also in the scripts folder).
If you open up the text file called linksPage.txt, you'll see that it's just a HTML table. To get this table into the PHP page called links.php, we just did this:
<?PHP include "linksPage.txt" ?>
The point is, if we had the include line on all pages of out site, and we had to add a new section, we could just change the text file linksPage.txt. This change would then mean that all the pages in the site would be updated!
Try it yourself. Add the following line to the page called linksPage.txt. Put it between the TABLE tags:
<TR>
<TD height="30" valign="middle" bgcolor="#FFFFCC">
<a href="links.php">New Section</a>
</TD>
</TR>
Save the page, and then load up links.php again. You should see a new section added to your menu bar.

Including Scripts

You can also use the include( ) function for scripts. You could include those valuable error checking functions that you've stored in one PHP file. Or just use it to cut down on the amount of code in the page.
As an example, load up the page called includeScript.php (in the scripts folder that you downloaded). The code is quite simple. It's just this:
<?PHP
include "myOtherScript.php";
print "This was printed from the includeScript.php";
print "<BR>";
doPrint();
?>
The above script uses include to include another PHP script - myOtherScript.php (also in the scripts folder). The function called doPrint() is in myOtherScript.php. If you open that file, you'll see it's just this:
<?PHP
function doPrint() {
print "This was printed from the myOtherScript.php";
}
?>
Load up the page called includeScript.php in your browser. You should see two lines printed out.

So, include is a very useful function – one of the most useful inbuilt PHP functions available to you!
In the next section, we'll look at some of the security issues with the code you've written so far. It's only a short section, but it's essential reading!

Comments