Introduction to Functions in PHP
Explore the concept of functions in PHP by understanding what they are, the difference between built-in and user-defined functions, and how to implement your own. Learn to write and call functions to perform specific tasks, preparing you for using parameters in the next lesson.
We'll cover the following...
What is a Function?
A function is a block of code that is written in order to perform a specific task.
Let’s discuss a real-life example to understand the concept better. Suppose that a headmaster wants a teacher to calculate the average marks of the students in a class for a particular subject. The teacher will note down all the marks of the students for that subject, perform the required calculations to calculate the average mark and then report the result to the headmaster.
Functions work in a similar way. They take the required information to perform a task as input parameter(s), perform the required operations on these parameters, and then they return the final answer.
Types of Functions
In PHP there are two major types of functions:
- Built-in functions
- User-defined functions
Built-in Functions
PHP already provides quite a few built-in functions that a user can use. These functions are pre-defined and just need to be called. Here is a list of built-in functions in PHP.
User-defined Functions
Apart from built-in functions, PHP also allows us to make our own customized functions. These functions can be written such that they would perform the required task wherever necessary once they’re called.
Implementation
Now let’s discuss the method to write a user-defined function below.
Example
Let’s take a look at an example now.
Explanation
As you can see from the example above:
Line 3
- You first write the keyword
function. - Next you write the name of the function, in this case, it’s
Examplefunc.
Line 5
- Then you write the body of the function in between the curly braces.
Line 9
- In the end, you simply call the function as can be seen in line 9 above.
In the example above, we didn’t pass any parameters to our function as there was no need. In the next lesson let’s look at what parameters are and how to pass them to our functions.