November 1, 2011 function_post

PHP Functions, an overview

This is a subject that some poeple might get confused at first, but it’s nothing to be afraid of. In fact, if you have already read my previous posts on PHP, you should have already seen some built in functions(mainly language constructs) in our scripts such as, isset(), trim(), empty(), count(), mail(), fopen(), fread() etc. I can keep on going. If you notice, these built-in functions may take a parameter. A parameter is a value being sent to the function, in which will affect the way the function will behave. The way the syntax is for any function in PHP is as follows:

This is a very simple function in PHP, and the name for this function is functionName. The function name comes right after the keyword ‘function’. This keyword will indicate that the following declaration is a PHP function. In order to execute what is inside the function, you need to make a call to the function. To call the previous function inside your script, you would do it very easy like this:

The advantage of having functions in you PHP scripts are that you can reuse code as much as it is needed. Let’s say that we need a script that would calculate different operations depending on the user input. In this example, we will use a function that can be used for the four(4) basic math operations. (Add, Subtract, Divide, Multiply). The function would need to take a few parameters, which will be 2 numbers, and an operation.

Note how there are three(3) parameters that this function will accept. Also notice that the third parameter, is what we know as an optional parameter. This means, that if I place nothing on the third parameter, and make the call like this:

This will automatically make the operation ‘add’ as a default calculation. Now that we know what our function does, let’s give it a test drive.

The output for this would be:

{php}
1 + 3 = 4
9 x 5 = 45
Division by zero test: Cannot divide by zero
{/php}

So here we saw, how to declare a default value for a parameter, how to call the function to be executed, and used a return value, to display the result on the screen. Any questions, just ask me.

One thought on “PHP Functions, an overview

Leave a Reply

Your email address will not be published. Required fields are marked *

The qTranslate Editor has disabled itself because it hasn't been tested with your Wordpress version yet. This is done to prevent Wordpress from malfunctioning. You can reenable it by clicking here (may cause data loss! Use at own risk!). To remove this message permanently, please update qTranslate to the corresponding version.