A function is a block of reusable code that performs a specific task. In PHP, functions are defined using the `function` keyword, followed by a name for the function, a set of parentheses, and a block of code enclosed in curly braces.
Here is an example of a simple PHP function:
“`php
function sayHello() {
echo “Hello, World!”;
}
“`
In this example, the `sayHello()` function simply outputs the string “Hello, World!” to the screen when called.
Functions can also accept parameters, which are values that are passed into the function when it is called. Here is an example of a function that accepts a parameter and displays it:
“`php
function sayHelloTo($name) {
echo “Hello, $name!”;
}
“`
In this example, the `sayHelloTo()` function accepts a parameter called `$name`, and then outputs a personalized greeting using that parameter.
Functions can also return values using the `return` keyword. Here is an example of a function that calculates the sum of two numbers and returns the result:
“`php
function add($a, $b) {
return $a + $b;
}
“`
In this example, the `add()` function accepts two parameters, `$a` and `$b`, and returns their sum.
To call a function in PHP, you simply type the function name followed by parentheses. For example, to call the `sayHello()` function from the first example, you would write:
“`php
sayHello();
“`
This would output “Hello, World!” to the screen. If a function expects parameters, you need to pass them in the parentheses. For example, to call the `sayHelloTo()` function with the name “John”:
“`php
sayHelloTo(“John”);
“`
This would output “Hello, John!” to the screen.