Functions
## Learning Objectives
- Create user-defined functions
- Understand parameters and return values
- Work with variable-length argument lists
- Master anonymous functions and closures
- Use arrow functions
## Defining Functions
### Basic Function
```php
```
### Function with Parameters
```php
```
### Return Values
```php
```
### Multiple Return Values (via Array)
```php
```
## Parameters
### Default Parameter Values
```php
```
### Positional vs Named Arguments (PHP 8)
```php
```
### Type Declarations
```php
```
### Nullable Types
```php
```
### Void Functions
```php
```
### Mixed Type (PHP 8)
```php
```
## Variable-Length Arguments
### func_get_args()
```php
```
### Spread Operator (...)
```php
```
### Fixed + Variable Args
```php
```
## Return Types
### Declaration
```php
```
### Union Types (PHP 8)
```php
```
## Anonymous Functions
### Basic Anonymous
```php
```
### Using use()
```php
```
### Changing Outer Variable
```php
```
## Arrow Functions (PHP 7.4+)
### Basic Arrow Function
```php
$x * 2;
echo $double(5); // 10
?>
```
### Arrow with Multiple Args
```php
$a + $b;
echo $add(3, 4); // 7
?>
```
### Arrow with Multiple Expressions
```php
$x * $factor + ($factor > 1 ? 5 : 0);
echo $calculator(3); // 11
?>
```
### Arrow vs Anonymous
```php
$x * $factor;
// Anonymous - must use 'use' explicitly
$anon = function($x) use ($factor) {
return $x * $factor;
};
?>
```
## Callable Type
### Using Functions as Arguments
```php
```
### Type Declarations for Callables
```php
print("Hi!\n"), 3);
?>
```
## Callback Functions
### array_map Callback
```php
```
### array_filter Callback
```php
```
### usort with Callback
```php
"Alice", "age" => 25],
["name" => "Bob", "age" => 30],
["name" => "Charlie", "age" => 20]
];
usort($people, function($a, $b) {
return $a["age"] <=> $b["age"];
});
print_r($people); // Sorted by age
?>
```
## Recursion
### Factorial
```php
```
### Fibonacci
```php
```
## Variable Functions
### Dynamic Function Calls
```php
```
### Method Variants
```php
$method(); // Calls $obj->myMethod()
?>
```
## Built-in Functions Reference
### Math Functions
```php
```
### String Functions
```php
```
## Summary
- Define functions with `function name() { }`
- Parameters with defaults: `function($x = 10)`
- Return values: `return $value;`
- Type declarations for parameters and returns
- Variable args: `...$args` (spread operator)
- Anonymous: `$func = function() { }`
- Arrow functions: `fn($x) => $x * 2`
- Use `use($var)` to capture outer variables in closures
- Use `&` to modify outer variables in closures
- Recursion: function calls itself
- Functions are first-class: can be assigned to variables
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →