Introduction to PHP Functions
Functions are a very important part of PHP and it is probably safe to say that they are used in every single script. This tutorial will guide you through the basics of PHP functions to creating your own to do specific tasks.
Functions: An Introduction
You have already used many functions with PHP. Every time you do:
explode(' ', $value1);
?>
you're using a function. These are known as built in PHP functions because they are the same and are available on every PHP setup. You can access them in any script without needing to do anything special.
A function can be classed as a subprogram that can act on data and return a value. Each function has its own name and when that name is encountered, the execution of the programme branches off to the first line (or statement) of that function. When the function has completed, it 'returns' and execution resumes from where it left off. A function will perform a specific task and do it well, returning the value you want with the arguments you pass to it.
When you lookup a function on the PHP website e.g
explode(), you will see the description of the function, and what it does first. The description then explains how to use the function.
In the case of explode:
array explode ( string separator, string string [, int limit])
This line is known as the prototype. It tells you exactly what the function is and what parameters it should be passed. We can see that it will return an array when you call it, and as parameters (the name of a variable usually passed to a function e.g
$split and
$string are the parameters in
explode($split, $string)), it takes separator, string and limit. Parameters are always within the
( ). The first 2:
( string separator, string string [, int limit])
are required and you must pass arguments (the actual value of the parameter e.g
' ' and
'split this up' are the arguments in
explode(' ', 'split this up')) for these when you call the function. If you do not specify a separator or a string, you will get an error. The parameters must also be passed in the order they are listed here. You cannot swap them around.
However, there is the limit parameter at the end:
( string separator, string string [, int limit] )
Notice how this is within [squared brackets]. This means it is optional. You do not need to pass that parameter to the function.
The return and parameter types (highlighted below) are not really important in most cases.
array explode ( string separator, string string [, int limit])
PHP is known as a loosely typed language which means you do not need to worry about variable types. PHP will do the work for you. In the case of
explode(), you know however that it will return an array when it is completed and you have to pass it 2 strings. You would get an error if you tried to pass it an integer:
explode(1, 15117);
But generally speaking, you can safely ignore the types.
When calling the function, you can do several things with the result. For example, you could echo it directly to the page:
echo explode(' ' , 'split this up');
Which wouldn't be much use. The most common thing you'd do is save the result in a variable like so:
$split = explode(' ' , 'split this up');
You can then play with the data as you like because it is in the $split variable.
Functions: Creating your own
The PHP functions are great. They do everything you need. However, what happens if you want to do the same thing over and over in a script? For example, in Olate Download 3.0, we want to format the date of the file in the same way every time. We could do:
$formatted_date = date('d/m/Y', $date);
wherever we want to set the formatting. But what if we want to change the way it is formatted in the future? We'd need to edit that line in lots of places throughout the entire application. This would be a pain.
So we created our own function to do this for us. This allows us to use the same code throughout the entire application but if we want to change it, we only need to do so in the function itself, not everywhere it is used. This function is a nice simple example that I shall use here.
The first thing you need to do when creating your own function is declare it. When you do this, you create the name of the function and define which parameters you want to be passed to it. You start the line with:
function
This tells PHP that you are declaring a function. Then you go ahead and give it a name, open brackets ( provide some parameters then close brackets ). So you get
function format_date($date)
You can call the function whatever you like as long as the name is not already used by a PHP function. However, it is common sense to call the function something useful.
function eat_pies($date)
Does not do what you expect. It does not actually have anything to do with eating, or pies...or even eating pies. It will format the date. The same applies with:
function a($date)
That is pointless. You have no idea what that does when you look at it. Similarly, because functions do something, you should try and get a verb in the name. Here we're using the verb 'format'. The function above
eat_pies() uses the verb 'eat'. It just makes it easier to understand what is going on.
Next you need to write the code that will be executed when you call your function:
function format_date($date)
{
$formatted_date = date('d/m/Y', $date);
return $formatted_date;
}
You can see that the code is contained within the curly braces
{ } just like with control structures such as if.
The first line of the function code is our date formatting code. When you call the function in your main script:
format_date('1088768118'); // 1088768118 is a unix timestamp. See the time() and date() functions for info
The argument
1088768118 will be stored in the
$date variable within the function. You can then access that data by using
$date just as you would if you had assigned the value doing:
$date = '1088768118';
The result of the formatting will then be stored in the variable
$formatted_date. The last line then returns that value. As soon as you specify return, the function will stop executing. So:
function format_date($date)
{
$formatted_date = date('d/m/Y', $date);
return $formatted_date;
// We have returned before this
$this = 'will not be set';
}
Now when I call:
$new_date = format_date('1088768118');
The result of the
format_date() function will be stored in the
$new_date function. And if I wanted to echo that directly to the page:
// Will display 02/07/2004
echo format_date('1088768118');
And there you have successfully created your own function. When you call it, it will be executed and the value will be returned for you to use.
You can put your function declarations wherever you like. But the best place is at the top of the file, or in a separate file than you can then include in every page you want to use the function in:
function format_date($date)
{
$formatted_date = date('d/m/Y', $date);
return $formatted_date;
}
// Will display 02/07/2004
echo format_date('1088768118');
?>
Functions: Variables within functions
This is slightly more complicated and is a common area for bugs when you're programming - variable scope.
If you create a variable in a function and assign a value to it, once the function has finished executing, that variable is destroyed and you cannot access it. You must return it or lose it:
function test_scope()
{
$this = 'that';
}
// Call the function
test_scope();
// Echo $this
echo $this;
?>
Won't work. If you want to do that, you need to do:
function test_scope()
{
$this = 'that';
return $this;
}
// Call the function
$this = test_scope();
// Echo $this
echo $this;
?>
where you are returning the value and then assigning it to a variable. Alternatively, you can do:
function test_scope()
{
$this = 'that';
echo $this;
}
// Call the function
$this = test_scope();
?>
You notice how I've used the echo function within my function. Wherever you call
test_scope() then the value of
$this will be echoed.
And that concludes the PHP functions tutorial. If you have any problems please post in the forums.