Defining and Calling Functions
Create your own functions with parameters and return values.
Why Functions?
Functions let you package reusable logic, giving it a name so you can call it many times without repeating code. Benefits:
- Avoid repetition (DRY principle)
- Easier testing and debugging
- Self-documenting code
Defining a Function
Use the function keyword, a name, optional parameters, and a body:
<?php
function greet(string $name): string {
return 'Hello, ' . $name . '!';
}
echo greet('Alice'); // Hello, Alice!All lessons in this course
- Defining and Calling Functions
- Default and Variadic Parameters
- Variable Scope: Local and Global
- Anonymous Functions and Closures