In PHP, a function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. In this tutorial, we will explore how to create and use functions in PHP.
A function in PHP starts with the keyword function, followed by the function name and parentheses (). The code inside the function is enclosed within curly braces {}. You can pass information to a function through parameters, which are variables that are used to receive values passed into the function.
function functionName($parameter1, $parameter2) {
// Code to execute
return $result;
}
- **Function Declaration**: The `function` keyword is followed by the function name and parentheses. If the function accepts parameters, they are listed inside the parentheses.
- **Function Body**: The code that defines what the function does is placed between curly braces `{}`.
- **Return Statement**: The `return` statement is used to send a value back from the function when it completes its task.
## Examples
### Example 1: Simple Function without Parameters
Let's create a simple function that prints "Hello, World!".
```php
<CodeBlock language="php">
{`function sayHello() {
echo "Hello, World!";
}
sayHello();`}
</CodeBlock>
When you run the above code, it will output:
Hello, World!
Now, let's create a function that takes parameters and returns their sum.
<CodeBlock language="php">
{`function add($a, $b) {
return $a + $b;
}
$result = add(5, 3);
echo "The sum is: " . $result;`}
</CodeBlock>
When you run the above code, it will output:
The sum is: 8
PHP also supports default parameter values. If a function is called without an argument for a parameter that has a default value, the default value is used.
<CodeBlock language="php">
{`function greet($name = "Guest") {
echo "Hello, $name!";
}
greet(); // Uses default value
greet("John"); // Overrides default value`}
</CodeBlock>
When you run the above code, it will output:
Hello, Guest! Hello, John!
In PHP, a function can return only one value. However, you can return an array or an object to simulate returning multiple values.
<CodeBlock language="php">
{`function getUserInfo() {
$name = "Alice";
$age = 30;
return [$name, $age];
}
list($name, $age) = getUserInfo();
echo "Name: $name, Age: $age";`}
</CodeBlock>
When you run the above code, it will output:
Name: Alice, Age: 30
In this tutorial, we covered the basics of creating and using functions in PHP. In the next section, we will delve deeper into user-defined functions, including more advanced concepts like variable-length argument lists and static variables.
Feel free to experiment with these examples and try creating your own functions to enhance your understanding!