PHP Tizag Tutorial-35
PHP Tizag Tutorial-35
A function is just a name we give to a block of code that can be executed whenever we need it. This might
not seem like that big of an idea, but believe me, when you understand and use functions you will be able to
save a ton of time and write code that is much more readable!
For example, you might have a company motto that you have to display at least once on every webpage.
If you don't, then you get fired! Well, being the savvy PHP programmer you are, you think to yourself, "this
sounds like a situation where I might need functions."
Tip: Although functions are often thought of as an advanced topic for beginning programmers to learn, if
you take it slow and stick with it, functions can be just minor speedbump in your programming career. So don't
give up if you functions confuse you at first!
When you create a function, you first need to give it a name, like myCompanyMotto. It's with this function
name that you will be able to call upon your function, so make it easy to type and understand.
The actual syntax for creating a function is pretty self-explanatory, but you can be the judge of that. First,
you must tell PHP that you want to create a function. You do this by typing the keyword function followed by
your function name and some other stuff (which we'll talk about later).
Here is how you would make a function called myCompanyMotto. Note: We still have to fill in the code for
myCompanyMotto.
PHP Code:
<?php
function myCompanyMotto(){
}
?>
Note: Your function name can start with a letter or underscore "_", but not a number!
With a properly formatted function in place, we can now fill in the code that we want our function to
execute. Do you see the curly braces in the above example "{ }"? These braces define where our function's
code goes. The opening curly brace "{" tells php that the function's code is starting and a closing curly brace "}"
tells PHP that our function is done!
We want our function to print out the company motto each time it's called, so that sounds like it's a job for
the echo function!
PHP Code:
<?php
function myCompanyMotto(){
echo "We deliver quantity, not quality!<br />";
}
?>
That's it! You have written your first PHP function from scratch! Notice that the code that appears within a
function is just the same as any other PHP code.