Functions
Functions are extremely useful things in programming, PHP isnt the only language with functions, so users from other languages such as C should feel right at home when using User Defined PHP Functions.
So What is a Function?
A Function is a small piece of organised code programmed to do a certain task. So why not just use the standard procedural approach?
Functions are a great thing they can be used more than once. So say you were creating a script that displays only php files in all directories from a certain level this would firstly require a script to firstly find the starting level, then find all directories. Then to read all directories. This is quite big script already, and say we than later on want to get only .html files as well. We would need to do this all over again.
<?php
//small skeleton example, not tested and the logic is probably not exact this is more of an overview
$dir = opendir("/my/path");
$files = array();
while (($file = readdir($dir)) !== false)
{
if (is_dir("/my/path/".$file))
{
$dirs[] = "/my/path/".$file;
// loop again
}
else
{
$path_parts = pathinfo("/my/path/".$file);
if (path_parts['extension'] == "php")
$files[] = "/my/path/".$file;
}
}
This technique in this situation is rather tedious and also very inefficient, a function is a much better alternative.
<?php
function getExFiles($path, $extension)
{
static $files = array();
if (is_dir($path))
{
if (substr($path, -1) == "/")
$path = substr($path, 0, -1); //get rid of /
$dh = opendir($path);
while (($file = readdir($dh)) !== false)
{
if ($file != '.' && $file != '..')
{
if (is_dir($path."/".$file))
{
getExFiles($path."/".$file, $extension);
}
else
{
$pathInfo = pathinfo($path."/".$file);
if (isset($pathInfo['extension']) && $pathInfo['extension'] == $extension)
$files[] = $path."/".$file;
}
}
}
return $files;
}
else
return false; //no point in continuing its not a directory bad call somewhere
}
print_r(getExFiles('/home/user/public_html','php'));
?>
As you can see thats the basis of the function. Quite small, now see as its looping through the directory than finds another directory and uses the function within the function. This is called recursion, basically looking at the script we are calling the same function within the function. Basically doing another entire loop itself.
Also we can use this more than once so instead of having to rewrite this function we can use it again and the benefit is that we can also change the extension
<?php
function getExFiles($path, $extension)
{
static $files = array();
if (is_dir($path))
{
if (substr($path, -1) == "/")
$path = substr($path, 0, -1); //get rid of /
$dh = opendir($path);
while (($file = readdir($dh)) !== false)
{
if ($file != '.' && $file != '..')
{
if (is_dir($path."/".$file))
{
getExFiles($path."/".$file, $extension);
}
else
{
$pathInfo = pathinfo($path."/".$file);
if (isset($pathInfo['extension']) && $pathInfo['extension'] == $extension)
$files[] = $path."/".$file;
}
}
}
return $files;
}
else
return false; //no point in continuing its not a directory bad call somewhere
}
print_r(getExFiles('/home/userl/public_html','html'));
?>
Hopefully you can see the advantage of functions. If not in time you will, this example is beyond most new users to PHP, however those coming from other languages should be able to see the logic. Unfortunately for those that dont copy it down and create a file and test. See what happens, play around with it.
How to use a Function
Most new users still use HTML inside there PHP File. Now personally I have nothing agaisnt them its all part of the learning curve however I tend to have the HTML and PHP seperate, this isnt part of the tutorial so I wont be showing a way to do this.
The basic idea of a function is really so it can be reused. If you only need to use something once the function is pointless and procedural programming is probably a better alternative, the other idea behind function is organisation. Organising code to be able to use them is a good habit to get into especially if you create useful functions which can be used in other projects.
Now since functions are there to be used more than once the function must return something to the script that called for the function.
<?php
function max($a,$b)
{
if ($a > $b)
return $a;
else
return $b;
}
?>
This is similar to that of the actual PHP Max function so dont use it as its already defined. But as you can see a variable is return either $a or $b;
Another way most new users to functions do is something like this
<?php
function max($a,$b)
{
if ($a > $b)
echo $a;
else
echo $b;
}
?>
Now there isnt anything really wrong with this, however what happens if we want a variable to be assigned to the max number, as you hopefully know echo is an output function so we cant get the number as its gone to output.
This is where return comes into the picture. A return doesnt really need to return anything useful we could return a boolean (true OR false). And a variable can be assigned to function and get return value. This is why the first max function is much better than the second.
With echo a lot of new users with using functions tend to want to have HTML put in the function, again there isnt anything wrong with this it will work however it tends to throw out the reason for functions which is to be able to reuse them.
What is an Argument
No not that type of argument when someone yells. An argument is what is assigned in the function
<?php
function func($arg1, $arg2);
?>
$arg1 and $arg2 are arguments for the function. However there is something else we need to learn parameters, lets go back to the max function
<?php
function max($a,$b)
{
if ($a > $b)
return $a;
else
return $b;
}
$max = max(1,5);
?>
As we can see we assigned a variable and than assigned it to the max function. So what is 1 and 5. Well they are the function paramters.
Defined Arguments
A defined argument is something that is associated to an argument variable, its the default value. E.g. we can make it that we dont want to have any parameters in a function yet we have 1 argument lets take a look at what I am on about.
<?php
function makecoffee($type = "cappuccino")
{
return "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee("espresso");
?>
As you can see $type is defaulted to cappuccino now the first call to the function will output
Making a cup of cappuccino
While the second will be
As you can see this is quite a useful task, we can make out functions more dynamic, and still make them reusable. [More Reading on Arguments]
Globals / Static
In our first example of a function there was a keyword used "static"
static $files = array();
So what does it do exactly?
You will find that static and global keywords will be something often used in functions more so global. Static allows the variable value to stay in the function so when its used again the value is still present. Now this makes the first function with directories not very well prepared you see if we want to get another extension it will be joined on with the last call.
<?php
function sum($a, $b)
{
static $c = 5;
$c += $a + $b;
return $c;
}
echo sum(5, 6); // will output 16 e.g $c = 5 + 5 + 6 = 16
echo sum(5, 6); // will output 27 e.g. $c = 16 + 5 + 6 = 27
?>
So what about global?
Global makes a variable that is outside a function accessible inside the function. This may be a better alternative then static in our directory example since it stay in the function, so once the function as finished the global can than retain the value.
So why not used global?
So global may seem like a very attractive option and it is and many PHP Programmers use it, I do. However global again just throws out the very existance of why the function was created. So it can be reused. Now if you want it only reused in the same script its alright go for it however what happens when you wish to use it in another script? Using global will basically need the function to be modified just to work.
What happens if you are working in a group, no one will really know about the global and will get unexpected results when using your function.
So when do i use global and static?
Well there is always a time. Now global can be used properly within a group project however it must be noted. A global if the variable doesnt exist outside the function will be created otherwise. Static on the other hand is useful if you wish to use results from prior calls to the function. Again it must be made aware to other programmers that first use will give correct output while using the function again will return unexpected results.
So whats the better alternative?
Using arguments in place of static and global, but remember the function may require results like with our sum to give weird results or use variables from outside however static is safer and is reusable while global isnt.
More reading in the Manual on functions which goes a little deeper than this tutorial PHP Manual on Functions