Functions are essential building blocks in PHP. They help us organize code, make it reusable, and prevent repetition. Let's explore how they work and what makes them special in PHP.
Basic Function Syntax
Creating a function in PHP starts with the function keyword, followed by the name and parentheses. The name should describe what the function does:
Parameters and Arguments
Functions become more useful when they can work with different values. We can pass data to functions through parameters:
Return Values
Functions can send back results using the return statement. A function can return any type of data - numbers, strings, arrays, or even other functions:
}
$status = getStatus(80); // returns: "Passed"
Default Parameter Values
PHP allows you to set default values for parameters. If an argument isn't provided, the default value is used:
Type Declarations
Since PHP 7, you can specify types for parameters and return values. This helps catch errors early and makes code more reliable:
Anonymous Functions (Closures)
PHP also supports anonymous functions, often used for callbacks or when a function is used only once: