PDA

View Full Version : Writing your first PHP Function



tkv
12-29-2007, 08:42 PM
A few days ago on the PHP list, I noticed a novice user asking a very simple question.... he needed to create a function for the first time and needed help. This tutorial goes out to anybody who is searching for a short, simple explanation on how a function should be written and used.

Functions are a great way to limit the amount of error in anything you need to do exactly the same way more than one time.. It also helps shortening the code you need to write down the line, saving you the time and troubleshooting a copy of the same snippet. Take the following example:


<?php
//simple snippet to show code repeating itself... adding days one by one and echoing them.
//get the current epoch timestamp
$timestamp = time();
//echo the timestamp;
echo $timestamp.'<br />';
//add a day to the timestamp(in seconds)
$timestamp = $timestamp + 86400;
//echo the timestamp again, showing the addition of a days worth of seconds. echo $timestamp.'<br />';
//add a day to the timestamp(in seconds)
$timestamp = $timestamp + 86400;
//echo the timestamp again, showing the addition of a days worth of seconds. echo $timestamp.'<br />';
?>

The code simply shows a repetative process of the same code, adding a day, and echoing it out. Now take a look at the same script with a function to add a day and return it.

<?php
//functioned version of echoing dates
function addDay($timestamp) {
//this function adds 86400 seconds to a epoch timestamp.
$newTimestamp = $timestamp + 86400;
return $newTimestamp;
}
$timestamp = time();
$aDayFromNow = addDay($timestamp);
$twoDaysFromNow = addDay($aDayFromNow);
echo 'Today: '.$timestamp.'<br />';
echo 'Tomorrow: '.$aDayFromNow.'<br />';
echo 'The Day after Tomorrow: '.$twoDaysFromNow.'<br />';
?>

This shows how a function can be used over and over again. Quite simply it does the same thing we had in the first script, but the function makes it an automatic process, and the only error that could occur, is a typo in the function name instead of, for instance, typing 86300 instead of 86400(because you had to type id again).
Now, lets extend that function, so we can add multiple days at a time, making it more usefull.

<?php
//functioned version of echoing dates
function addDay($timestamp, $numDays = 1) {
//this function adds 86400 seconds to a epoch timestamp.
$secondsToAdd = $numDays * 86400;

$newTimestamp = $timestamp + $secondsToAdd;

return $newTimestamp;
}

$timestamp = time();

echo 'Today: '.$timestamp.'<br />';
echo 'Tomorrow: '.addDay($timestamp).'<br />';
echo 'The Day after Tomorrow: '.addDay($timeStamp,'2').'<br />';
?>
Notice how simple it is to use the function as opposed to the original code! We've also added in another feature of functions. You'll notice that in this previous example, $numDays = '1', this allows us to set a defualt value, if none is set for the variable. as you can see, to echo tomorrow's timestamp we only used addDay($timestamp) and NOT addDay($timeStamp,'1'). Though the mean the same thing, it allows for quicker coding, assuming you know the attributes requested by the function.
Now we'll look at how the variables are available. In the last few short scripts, the function had variables passed to it. Unless otherwise specified, variables inside of a function, don't have access to variables outside of the function, and vice versae.

<?php
$externalVariable = "Hello, I'm the external variable";
function printVariables() {
//this function tries to print $externalVariable as well as $internalVariable
echo "echoing from inside the function<br />";
echo $externalVariable.'<br />';
$internalVariable = "Hello, I'm an internal variable";
echo $internalVariable.'<br />';
}
printVariables();
//now we'll echo the internal and external variable outside of the function
echo "<br /><br />Now Printing outside the function<br />";
echo $externalVariable.'<br />';
echo $internalVariable.'<br />';
?>
output:

echoing from inside the function
Hello, I'm an internal variable

Now Printing outside the function
Hello, I'm the external variable

To allow access to external variables inside of the function, we can specify them by adding the line "global $externalVariable;" See the code below, and output:

<?php
$externalVariable = "Hello, I'm the external variable";
function printVariables() {
global $externalVariable;
//this function tries to print $externalVariable as well as $internalVariable
echo "echoing from inside the function<br />";
echo $externalVariable.'<br />';
$internalVariable = "Hello, I'm an internal variable";
echo $internalVariable.'<br />';
}
printVariables();

//now we'll echo the internal and external variable outside of the function

echo "<br /><br />Now Printing outside the function<br />";
echo $externalVariable.'<br />';
echo $internalVariable.'<br />';
?>
output:

echoing from inside the function
Hello, I'm the external variable
Hello, I'm an internal variable

Now Printing outside the function
Hello, I'm the external variable

Plain and simple, now we have access to the exernal variable. But what if we want to give access to the internal variable outside of the function(never really used, but put in for an example):

<?php
$externalVariable = "Hello, I'm the external variable";
function printVariables() {
global $externalVariable, $internalVariable;
//this function tries to print $externalVariable as well as $internalVariable
echo "echoing from inside the function<br />";
echo $externalVariable.'<br />';
$internalVariable = "Hello, I'm an internal variable";
echo $internalVariable.'<br />';
}
printVariables();

//now we'll echo the internal and external variable outside of the function

echo "<br /><br />Now Printing outside the function<br />";
echo $externalVariable.'<br />';
echo $internalVariable.'<br />';
?>
output:

echoing from inside the function
Hello, I'm the external variable
Hello, I'm an internal variable

Now Printing outside the function
Hello, I'm the external variable
Hello, I'm an internal variable

As you can see, we now have access to the internal variable, because it has been specified as a global variable at the beginning of the function. You must remember though, that the variables that you specify as global, once in the function, will be altered in whatever way you have set inside of the function. In my personal opion, I try to stay away from using global variables as much as possible, unless its something like a database connection. There is another way to affect an outside variable from inside the function, or at calling of the function. Look below:

<?php
$externalVariable = "Hello, I'm the external variable";
echo $externalVariable.'<br />';
function printVariables(&$externalVariable) {
//this function tries to print $externalVariable as well as $internalVariable
echo "echoing from inside the function<br />";
$externalVariable = $externalVariable.', now I have something added on!';
echo $externalVariable.'<br />';
$internalVariable = "Hello, I'm an internal variable";
echo $internalVariable.'<br />';
}

printVariables($externalVariable);

//now we'll echo the internal and external variable outside of the function

echo "<br /><br />Now Printing outside the function<br />";
echo $externalVariable.'<br />';
echo $internalVariable.'<br />';
?>
Hello, I'm the external variable
echoing from inside the function
Hello, I'm the external variable, now I have something added on!
Hello, I'm an internal variable
Now Printing outside the function
Hello, I'm the external variable, now I have something added on!

By adding an ampersand(&) to the beginning of the string in the function declaration, we tell the function that it needs the use the variable reference, and not the variable value. This way, anything that happens inside the function affects the variable passed to it. This can also be done when calling the function for use by placing an ampersand(&) before the string there aswell. See below:



<?php
$externalVariable = "Hello, I'm the external variable";
echo $externalVariable.'<br />';

function printVariables($externalVariable) {
//this function tries to print $externalVariable as well as $internalVariable
echo "echoing from inside the function<br />";
$externalVariable = $externalVariable.', now I have something added on!';
echo $externalVariable.'<br />';
$internalVariable = "Hello, I'm an internal variable";
echo $internalVariable.'<br />';
}

printVariables(&$externalVariable);

//now we'll echo the internal and external variable outside of the function

echo "<br /><br />Now Printing outside the function<br />";
echo $externalVariable.'<br />';
echo $internalVariable.'<br />';
?>
output:

Hello, I'm the external variable
echoing from inside the function
Hello, I'm the external variable, now I have something added on!
Hello, I'm an internal variable

Now Printing outside the function
Hello, I'm the external variable, now I have something added on!

There we go, you now have several options for working with variables inside of functions, most of the time, I wouldn't reccomend referencing variables(adding &), or globalizing a variable in a function, unless it's a database connection string or something of that sort that isn't going to be changed. Another rule of thumb, is to return variables or arrays from a function... if you need to echo them, then echo them after passing the value or array to a variable when calling the function, then echo that. This makes your functions more useable. I hope this tutorial helps, if I had a tutorial like this when I was learning php, it would have saved me alot of time!