PHP Functions: Parameters, Return Types, and Scope
Functions group related instructions behind a reusable name. They help reduce duplication, make code easier to test, and give complex tasks a clear structure.
Defining a Function
Use the function keyword, a name, parentheses, and a code block.
function greet(string $name): string
{
return "Hello, " . $name;
}
$message = greet("Ava");
echo $message;
The parameter type documents what the function expects. The return type documents what it provides. Type declarations make interfaces clearer and help PHP detect incorrect values.
Parameters and Default Values
A function can accept multiple parameters. Optional parameters can have default values, and variadic parameters can collect a variable number of arguments.
function calculateTotal(float $price, int $quantity = 1): float
{
return $price * $quantity;
}
$total = calculateTotal(19.95, 3);
Choose parameter names that explain the purpose of each value. Avoid functions with too many unrelated parameters; a small value object or associative structure may be more suitable.
Variable Scope
Variables declared inside a function are local to that function. They are not automatically available outside it.
$siteName = "Info4PHP";
function getWelcomeMessage(string $name): string
{
return "Welcome, " . $name;
}
Passing values as parameters is generally clearer than depending on global variables. It makes dependencies visible and simplifies testing.
Returning Values
Use return to send a result back to the caller. A function may return a scalar, an array, or an object. A void return type indicates that the function does not return a value.
Practical Guidelines
Keep functions focused on one responsibility, validate arguments when necessary, use type declarations consistently, and avoid hidden side effects. Document non-obvious behavior with concise comments.
Conclusion
Well-designed functions make PHP applications more modular. Clear parameters, return types, and scope rules help keep code predictable as a project grows.