A function in PHP can save a lot of time by letting you quickly reuse a set of code. You will often have to use the same PHP code in many different spots. If it’s only one line of code, that’s no big deal. But what if it’s 10 lines, or 100 lines? You could copy and paste the code over and over, but that will start to look messy after a while. Creating your own functions enables you to store a bunch of code and refer to it easily.
PHP contains many pre-built functions. Back in the Testing Our Installation tutorial, we used the phpinfo() function. Besides the functions built into PHP, you could also install PHP extensions that give you even more functions to use. The official web site of PHP.net has a list of all their functions and sample usage. To quickly see a function, use the shortcut: www.php.net/Function_Name_Here
Not only do functions make your code cleaner to look at, but it makes your code easier to maintain. If you ever need to update your code in a function, you just update it in one spot. If you weren’t using functions and just copy and pasted your code everywhere, then you’d have to go into every file and make your changes. Like an old sandwich, this invites room for bugs and is a waste of your time. Functions are a key part of modular code which helps keep your scripts manageable.
Let’s build our own function. When naming a function, we end it with parentheses. Function names can contain numbers, but they can’t begin with a number. Let’s say we want to include the same message in many of our PHP files. Here’s one way to do it using functions:
<?php function my_message() { echo "Thank you very much for coming to my site!<br />"; echo "Please come back soon to see my latest updates.<br />"; echo "You can also email me with any questions.<br />"; } ?>
What we have here is a very basic function that consists of three echo statements. Let’s say I want to put it at the end of all my posts. Once I’ve created this function in my PHP file, I can refer to it later on by doing this:
<?php my_message(); ?>
And that’s it! Wherever I put my_message(), PHP will act as if I wrote the three lines of echo code we made above.
There’s much more to learn about PHP functions. Let’s continue to More With PHP Functions.
Go back to Building PHP Scripts.