To declare a function in PHP, you’ll need to use the `function` keyword followed by the function name, parentheses, and curly braces that encapsulate the block of code to be executed when the function is called. Here’s a detailed breakdown with examples and references to reliable sources.
The most basic syntax for declaring a function in PHP is:
```
function functionName() {
// Code to be executed
}
```
Let’s create a simple function that prints a greeting:
```
function sayHello() {
echo “Hello, World!”;
}
// Call the function
sayHello();
```
When you call `sayHello()`, the output will be:
```
Hello, World!
```
Functions in PHP can take parameters, allowing you to pass values into them:
```
function greet($name) {
echo “Hello, $name!”;
}
// Call the function with a parameter
greet(“Alice”);
```
The output when calling `greet(“Alice”)` will be:
```
Hello, Alice!
```
Functions can also return values using the `return` statement:
```
function add($a, $b) {
return $a + $b;
}
// Call the function and store the result
$result = add(5, 3);
echo $result;
```
The output is:
```
8
```
PHP allows you to set default values for parameters. If the function is called without an argument, the default value is used:
```
function greet($name = “World”) {
echo “Hello, $name!”;
}
greet(); // Uses default value
greet(“Alice”); // Uses provided value
```
The first call to `greet()` outputs:
```
Hello, World!
```
And the second call to `greet(“Alice”)` outputs:
```
Hello, Alice!
```
You can also specify the types of parameters and return values (available from PHP 7 onwards):
```
function multiply(int $a, int $b): int {
return $a * $b;
}
echo multiply(4, 3); // Outputs 12
```
PHP supports variadic functions, which allow you to accept an indefinite number of arguments:
```
function sum(…$numbers) {
return array_sum($numbers);
}
echo sum(1, 2, 3, 4); // Outputs 10
```
Here are some reliable and recognized sources where you can find more information about PHP functions:
1. PHP Manual: The official PHP documentation provides comprehensive details about functions:
- [PHP Functions](https://www.php.net/manual/en/language.functions.php)
1. W3Schools: Offers tutorials and examples on PHP functions:
- [PHP Function](https://www.w3schools.com/php/php_functions.asp)
1. Stack Overflow: A community-driven Q&A platform where you can find various discussions and examples:
- [Stack Overflow – PHP Functions](https://stackoverflow.com/questions/tagged/php+functions)
These sources are well-regarded within the programming community for their accuracy and extensive information. By referring to them, you can deepen your understanding of PHP functions and explore more advanced topics.