Functions are the lifeblood of PHP. You can’t do a lot without PHP’s built-in functions, and life would get very tedious very quickly if you weren’t able to define your own in a script.

Let’s take, for example, one of my scripts: BellaBook. BellaBook is a flat file guestbook and so constantly writes to files. It writes to a file when you submit an entry, it writes to a file if I approve, edit or even delete an entry. There’s a whole lot of file writing going on. Imagine how difficult to maintain the script would become if that file writing — which is effectively the same code — was written in 6-7 different places that you had to update each time? Well, I can tell you, because that’s how it started out… boring! It got very easy to make mistakes. By creating one function with one set of code that I could then simply reference as many times as needed, I eradicated many of the maintenance problems I was having.

So, now you know the why, but what about the how?

The basic syntax for creating a function is as follows:

function myFunctionName() {

}

Functions always start with function, and should start with a letter or number (like $variables). Always try to give function names that correspond to what the function is doing, as it’ll make your life easier in the long run (finding function1($var); in a script will throw up a wall, whereas you can immediately guess what multiplyBy2($var); does.) Inside the curly braces we can place the code we’ll need to use.

In our simple example, we shall echo a greeting with our function. We could simply write the greeting on each page, but — going back to what I said earlier — imagine how tedious it would be to update if we wanted to change that greeting later on? So, we start with our base syntax, and our echo inside the curly braces:

function greeting() {
    echo 'Good morning!';
}

You can then call this whenever you like using greeting(); (or <?php greeting(); ?> if you’re not already within a PHP block). Each time you put this on page, you will see “Good morning!“.

“Good morning!” isn’t very useful if it’s the middle of the afternoon, or if we want to specify our own greeting. To combat this limitation, we can pass a variable with our custom greeting to the function; or, if none is set, show the standard greeting. Variables are passed between the “( )” in the function declaration, like so:

function greeting($var)

So, changing our function to:

function greeting($greet) {
    if (!empty($greet))
        echo $greet;
    else
        echo 'Good morning!';
}

We can then choose to rely on the standard greeting using <?php greeting(); ?> with no variable, or specify our own: <?php greeting("Good evening!"); ?>. The data inside the quotes is available as our $greet variable inside the function.

If we were to pass two variables, e.g. function greeting($var, $var2), we would be able to provide two lots of data, e.g. <?php greeting("Good evening!", "Second bit of data"); ?>

Once passed, variables can then be used inside the function as with $greet above. However, variables created or modified inside the function can not be used outside of the function. This is what’s known as “scope”. Take for example, this snippet of code:

$newgreeting = 'Oh hi there';
function greeting() {
    echo $newgreeting;
}

If you used this code, and tried to echo your greeting by way of <?php greeting(); ?>, you’d get an undefined variable error. Because the $newgreeting variable was created outside of the scope of the function, it cannot then be used inside.

Functions are important to get right, but a pain in the bum to get used to. Practice creating your own functions using basic mathematical operators to get to grips with how function scope affects variables inside and outside of your functions. Next time, I’ll try to cover global scope, and default arguments.

php beginner's guideThis article is part of the Beginner’s Guide to PHP series. You can see all the guides or wait for Part Seven to be written ;)

Comments

  1. says

    I’m glad you are writing these still.. I got a book once on PHP and started freaking out because it just said things like "fsdjkfhdjk = gdsgd" but didn’t tell WHY or HOW and I am just one of those people who need to know WHY things work the way they do in order to understand it. :D

  2. Mat says

    Not bad, you might want to mention return values as they are expected in every function. Even if you return nothing PHP’s return for that function is simply assumed as NULL.

  3. says

    It might be worth mentioning that:

    function greeting($greet) {
    if (!empty($greet))
    echo $greet;
    else
    echo ‘Good morning!';
    }

    can be greatly simplified to:
    function greeting($greet=’Good morning!’) {
    echo $greet;
    }

    The =value in the argument list basically means that if a value isn’t passed, use this instead. That way you can have ‘optional’ parameters like so:

    listPosts($num=10, $start=0) {}

  4. Mat says

    @Luke: "Next time, I’ll try to cover global scope, and default arguments"
    Sounds like that was next on Jem’s list.

  5. TWD says

    Ooh, another guide! Thanks, Jem. :D I just want to be clear on the scope: if you define any variable someplace outside of your created function, you can’t pass it through the function? That seems a bit impractical to me-what if I wanted to run various pieces of data through that same function and the data was created elsewhere, say via a form that was submitted? Or would I use a loop for that? Also, does the scope bit apply to built-in PHP functions? (Sorry if these questions will be answered in a future piece! e_e)

  6. says

    This was really helpful to me… Part Six?!

    If only you had a search function, I’d find/read the other parts.

    P.S. Your website was down earlier.

Trackbacks