In this tutorial I will teach you how to define your own functions. You will see basic functions to complete common tasks or simple examples which are purely useless but show you key concepts in defining your own functions.
I'm sure you've all worked with functions, such as str_replace(), substr(), mysql_connect(), isset(), etc. They're all functions. There are, of course, differences in the functions themselves. From the naming styles, to the returned value types, to the overall purpose.
I'll be explaining how to decide which value types the function should return and how we decide whether to use a return value at all. I'll also be talking slightly in-depth about the features of code blocks and what should be kept in mind while dealing with them.
When you define a function, one keyword is needed to let the PHP engine know what you're trying to do. The keyword we're looking for is the function keyword. A basic function definition is done like so:
function functionName( argument list ) {
// some code
}
If you recall, most functions require what we call arguments, or values passed to the function to be modified, checked, verified, or other common tasks. However, some functions don't require any arguments, such as the phpinfo() function or the get_magic_quotes_*() functions. The same thing applies to user defined functions, they may or may not require arguments just as they may or may not return a value.
Let's go ahead and define a simple function. This function will simply add two values passed to it. While it's a basically worthless function, it shows how they're defined, etc.
function add($num1, $num2) {
return $num1+$num2;
}
Before you freak out over the return construct, let me explain the other parts of the code. This function's name is add and it accepts two arguments, which are both (supposed to be) numbers of some sort.
Remember how we use functions such as str_replace()? Let's say we pass a string to str_replace() like so and modify it.
$newStr = str_replace('shit', '%#^!', 'This is some horse shit');
Our new string would read: "This is some horse %#^!" and would be more reader friendly because we've censored out a curse word. Well, the returned value of this function is what is stored in the $newStr variable, or the string "This is some horse %#^!". Another way to think of a return value is the value that the function produces after performing the selected operations. Simple enough, right?
Let's show how we would call this function in our code.
echo 'The value of 2 plus 2 is ' . add(2, 2);
This would output "The value of 2 plus 2 is 4". Now, lets say you forgot to specify the second argument (or both arguments for that matter) while you were calling the function. You would get an error message similar to this one:
Warning: Missing argument 2 for add(), called in [remote path to file] on line [line of error] and defined in [remote path to file]
While this is not a fatal error and can be turned off with simple error handling functions (or in php.ini settings), it shouldn't be ignored. But what if we want a function to contain optional arguments like many functions, such as file(), fopen(), etc, do? Well, we can make arguments optional by specifying a default value in the parameter list while defining the function.
Let's modify the add() function we've already defined. Say we want it to require 2 numbers and be able to accept a 3rd number to add to the value. We could do so like this:
function add($num1, $num2, $num3 = 0) {
return $num1 + $num2 + $num3;
}
Now if we call this function like so:
add(2, 2, 5);
It would return the value 9, since 2 + 2 + 5 = 9. But let's say we only want to use two arguments and do it like this:
add(4, 20);
This would return 24 and WOULD NOT trigger the error shown above, because the third parameter of the function is optional! Now, sometimes optional parameters are used for brievity while coding. Let's say we create an incrementing function. Well, by default (and in most cases) we only want to increment our numbers by 1, so that would be assigned to the default value of the incrementing variable. Let's look at some code:
function inc($num, $val=1) {
return $num + $val;
}
Now, in most cases we could call the function like this:
inc(2); // Returns 3
But we could also do it like this:
inc(2, 6); // Returns 8
So now we have a concept down of defining functions, defining an argument list and using optional arguments with default values. Before I go on with this tutorial, I'm sure there are some of you out there scratching your heads about the terms "argument" and "parameter". Well, there is no real difference between these terms. They both describe the values passed to a function. But "argument" is usually the term chosen for discussing values passed to the function outside of the function. Likewise, "parameter" is used when you're talking about them inside of the function code block. That may sound confusing so let me draw you an example:
// Create the add() function with two required arguments and 1 optional argument
function add($num1, $num2, $num3=0) {
// $num3 is the optional parameter and $num1 and $num2 are required parameters
}
The difference is so minute they are almost (and usually) used interchangeably. Now that we've declared functions that return values, let's write some that don't return values but still acheive a purpose, even if it's useless.
Let's create a function which recreates the echo construct.
function outputContent($content) {
echo $content;
}
Now, if we call the function like this:
$returnedValue = outputContent('hello world!');
This will output "hello world!" on the user's screen; however, if we try echoing the value of $returnedValue which stores the returned value of the function (or lack of one, rather), then it won't output anything. Why you ask? It's because the function doesn't actually return anything at all. In fact, the value of $returnedValue is simply NULL, meaning no value at all.
Earn real money by betting and investing; or, sponsor, challenge, compete,
recruit, communicate, network, earn money playing games, and much more.