Using User-Defined Functions in PHP
PHP has over 1000 built in functions. However, the power of being able to use your own user-defined functions adds real flexibility.
To define a function we start with the word 'function' and then give the function a name followed by parentheses and then curly braces as follows:
Any code we wish to execute within the function goes between the curly braces:
So, let's take a very simple example which will echo out "Hello, World!".
Line 3: we have defined the function with a name of helloWorld.
Line 5: the content of the function is simply to echo out Hello, World!
HOWEVER, if we run this code nothing will happen. Although we have defined a function we have yet to call the function. To do so we have to do the following:
Line 9: we call the function helloWorld!
USING ARGUMENTS
We can pass information to functions by using arguments.
For example, if we have a function which adds two numbers then we can pass those numbers to the function as follows:
Line 3: we have a function called addNumbers and it is expecting 2 values which we are calling $number1 and $number2
Line 5: we take the 2 numbers and add them together and assign the value to $answer
Line 6: we echo out the answer
Line 10: we call the function and pass in the arguments 3 and 5. These are the 2 numbers which will be added together.
The output will be:
RETURNING VALUES FROM FUNCTIONS
Sometimes we may wish to return a value from a function rather than echo out the value as in the previous example.
Line 6: the $answer variable is returned to the function call on line 10
Line 10: we have defined a variable called $returnedAnswer which will take the result of the function i.e. the $answer variable.
If you would like to learn more about PHP then enrol in the PHP for Beginners course now.