PHP Tutorial: Functions

Nov 18th, 2000 | By

Print this article


PHP Tutorial: Functions


Date
: 11/18/00 – 03:30:27 AM

Author
:

Category
: Programming

Note: If you haven't read my introduction to to PHP(basics), read it here.

I was trying to decide which topic to cover next in my series of PHP tutorials when it came to me that arguably the most important aspect of PHP is functions. Sure, functions are important for every language, but doubly so for PHP since it uses not only pre-defined functions for everything, but the programmer may also declare functions as one sees fit. The hardest thing about programming will always be new concepts. It's easy to stay with simple things that you know in programming, and to stay clear from the difficult stuff. I can understand this as well as anyone else out there. Functions is one of those concepts that most people don't quite understand the first time they see them. If you have experience in Calculus or some such math, you probably have a good idea of the concept, but otherwise, you probably won't.

Here's a great explanations of functions that Jerome(pimp daddy) wrote for me after reading a preliminary copy of this article. I'm just going to paste in a bit of it, because he wrote it out in a way that made a good deal of sense.

Functions make the world a better place to live in. You probably run a few
functions each day that you're not aware of. If you keep a list of things
you need to get done today, the list itself can be thought as your main
program, and each item on the "To Do" list is a function. Each function
can run independently of other functions; "take out the trash" on the "To
Do" list doesn't have to depend on "wash the dishes." When you "run" your
"take out the trash" function, you perform a series of steps, complete the
task, and exit that function. Then, you can do something else.

A function is a little sub-program inside the main program. Functions help
break out your code into more easily-to-understand sections and they can be
used to simplify steps that you frequently go through.

If you want a coding example, if you start every page you make with the
phrase "Hello World!", you could type print "Hello World!" at the
beginning of every program. Or, you could make a function that you can
refer to every time you want to say "Hello World!".

Functions can do more than just execute a few lines of code. You can feed
a function input and it can spit out a result. For example, you could have
a function that adds two numbers. When you use the function, it prints out
what the sum of those numbers is. Or, you could return the sum of
the two numbers into another variable.

He said it there better than I could, so I just pasted in a few choice paragraphs. Let's move onto a few examples of what Jerry was talking about. Here's a short function example so you can see what I'm talking about.

function testfunc()
{
$blah = 4;
return $blah;
}
$five = testfunc();
echo $five;

Let's go through this example step by step. First of all, you open up the program with
<?php
, then we see something new here. In many programming languages, you need to declare your function as a specific datatype(integer, floating point, char), much like with regular variables. This is one of the great things about PHP, not only do you not have to declare a specific data type for a variable, but you don't have to for a function either. You just need to put the word function there. After function, you have the name of the function, followed up with two opening and closing parentheses, which will be explained soon. Also, notice how there is no semicolon at the end there. After the name, you have the opening brackets of the function, as well as the closing brackets, which you ALWAYS need. One you get past that, notice how I indent a little for what's inside the function. The computer doesn't really care how you space the code, and it may not seem like much now, but when you have hundreds of lines of code(at least), as well as many functions and other things, it gets a little hairy. This just helps the human out a little. Anyway, inside the function, I declare the variable
$blah
, and give it the value 4. The next line is something new though. I have the term
return
there, with the
$blah
variable right after it. This denotes that I'm returning the variable as the result of the function. You don't always have to return something..you can just print the result to the screen if you feel like it. But, you'll see the need for this soon.

Once you close the function, you get to the fun part. I've got a variable called
$five
into which I've stored the result of the function
testfunc()
. Just having the words
testfunc();
will "call" the function, but since you aren't storing it anywhere, or outputting it, nothing happens and the program moves on. This way, the result is stored in
$five
. Let me try to explain this a little further if I can. You have the function there, and then, in the main part of the program, you basically call it up from memory. Just for curiosity's sake, here's what the program would look like without a function.

$blah = 4;
echo $blah;

Does it look a lot simpler here? You bet it does. Unfortunately, not all code is two lines long. When you have much more code, functions is a great way of sorting things out easily and painlessly. You can have a separate function for doing each different thing you want to do. When you look at it, it's a great feature, and very important.

Now that I hope you have that basic function down(hope you tested it out yourself), let's get a little more complex. Here is a function that has a variable being passed to it!

$bubbles = 1;
function testfunc($b)
{
$b = $b + 4;
return $b;
}
$five = testfunc($bubbles);
echo $five;

Take a look at the differences between this codelet, and the one up above. First of all, I have the variable bubbles with the value 1 in it. Since the browser looks over functions until they are called, let's move on below it, and see where I've called the function. I call the function, and send it
$bubbles
. Once inside the function, notice the variable I'm using.
$b
?! That's right. The variable inside the function is what is called a
local
variable. It's local in that once inside the function it's a totally separate world from the outside. If there is a variable sent to the function, it gets the value, and whatever variable name is there, it uses that. In that sense, it's like you're declaring the variable
$b
totally separately from the main program, and it's only for use with the testfunc() function. When declaring it, you're sending it the value that is in
$bubbles
. If you try to do this, then outside of the function you try outputting
$b
, you won't get anything. It's
local
! There are global variables as well, with which you can output them anywhere, but we'll get to that later. Let me just get a little more complicated now, and show you some more. If you send a function two values, it'll look something like this.

function testfunc($a, $b)
{
$a = $a + $b;
return $a;
}
$five = testfunc(3, 4);
echo $five;

Let me just say this now, you can only return one variable from a function. You can output as many variables as you want, but you can't return more than one. I won't spend much time on this example, but you should be able to tell what's going on if you look through it line by line. I sent the function those two values, 3 and 4. The testfunc() function then declared it's own two variables, giving the value of 3 to
$a
, and 4 to
$b
. After that, I just added the two numbers, and returned
$a
.
$five
should output the value 7.
There is no set order for you to call a function in PHP. You can call it above the function code, or below it. It will give you the same answer every time.

Functions can be used in other ways aside from what I've shown here. They can be used in mathematical equations, as well as printing text, or HTML, or whatever. Here's one in an equation.

$a = 5;
$num = $a + testfunc();
echo $num;
function testfunc()
{
$b = 10;
return $b;
}

Using this, you can call a function on the spur of the moment, or whenever. Notice I also called the function above the actual function code, so this is possible. In C++, if you aren't calling the function below the actual function code, you need to declare it above at the top of the program. This can be a little annoying at times, but also can be good to know what's going on exactly.

Before you move onto the next thing, I would like you to try a few things out yourself and get the hang of the above. Come up with some things to do, and get comfortable with local variables, because next is the discussion of reference variables. Reference variables are not an easy concept to get your head around, especially if you have no previous experience in programming. I'll do my best trying to explain them, but let me know if you still don't know what I'm talking about at the end. Reference variables are used with functions to make the variable "global" in a sense. This means the variable is recognized everywhere in the code, not just in the function it's declared in. If you declare a variable outside a function, call the function and send the variable, and then make it a reference variable inside the function, whatever value you put in that variable will now be the globally recognized one. Here's an example.

$a = 5;
$b = 1;
echo $a + $b . "";
$num = $a + testfunc($b);
echo $num . "";
echo $b;
function testfunc(
&
$b)
{
$b = 10;
return $b;
}

I tried here to show the best way I could, the way the
$b
variable changed once it went through the function. Notice the ampersand(&) I put in the function there. That is the sign that makes something a reference variable. Put that in front of something, and it becomes reference. Let's go through what the code is doing exactly. I declare
$a
as 5, and
$b
as 1. I add both variables together, and print them out. The output is
6
. After that, I add together
$a
and the result of the
testfunc($b)
function. I send
$b
to the function, and make it a reference variable. In the function, I set
$b
to equal 10, and then return it. So,
$a
added to the result of
testfunc($b)
equals
15
. I output that, and then I output
$b
, which is going to be displayed as
10
. You might be thinking, "But Adam, you just declared $b as 1 right above it..and it's not in the function!". That's the point of this exactly. Making the variable reference sets it permanently and globably as that value. Only sending that variable to another function without making it reference, or just reassigning the value will change the variable at that point. So the output of this program will look like this…

6
15
10

This is not an easy concept for beginners to totally get their head around. If you don't understand it, you aren't stupid or anything. Just leave a comment in the comments and I'll read it and answer any questions you have.

There are an infinite number of ways to use functions, and I'm not really even scratching the surface here, but this is mostly just to get you on the road to knowing more. Predefined functions are a HUGE part of PHP. What are predefined functions you ask? Almost everything in PHP is a function in one way or another.
Echo
is a function, as well as
print
. You don't need parentheses for those though, but using
print("Hello World");
will print
Hello World
just as well as
print "Hello World";
will. Aside from these basic ones, there are hundreds of predefined functions listed in the php.net Online Documentation. I've spent hours looking through this manual, figuring out what everything does. There's a function that rounds numbers off, there are some that look for strings in other strings, there are some that compare two strings to see if they equal, or to get the absolute value of a number. Just take a look, and you will be pretty much amazed at the sheer amount of stuff you will find. Since it's pretty useless for me to go over these, I'll leave you to it.

Assignment(s)

  • Make a function that displays a word in the browser title bar. It's similar to the first article's assignment, but do it with a function this time.
  • Go back to the last article again, and do the work time program again, but when you do, display the time worked from a function.

Leave Comment

You must be logged in to post a comment.