Lesson 6 • Intermediate
Functions ⚡
Write reusable PHP functions with parameters, return types, closures, arrow functions, and PHP 8's named arguments.
What You'll Learn in This Lesson
- • Declaring functions with parameters and default values
- • Return types and nullable types (PHP 7+)
- • Variable scope: local, global, and static
- • Anonymous functions, closures, and arrow functions (PHP 7.4+)
- • Variadic functions (...$args) and named arguments (PHP 8)
1️⃣ Function Syntax
<?php
// Basic function
function greet(string $name): string {
return "Hello, $name!";
}
// Default parameter
function tax(float $price, float $rate = 0.20): float {
return $price * (1 + $rate);
}
// Nullable return type
function findUser(int $id): ?array {
// returns array or null
}
// Void return type
function logMessage(string $msg): void {
error_log($msg);
}
?>Try It: Basic Functions
Create functions with parameters, defaults, return values, and type declarations
// PHP Functions (simulated in JavaScript)
console.log("=== Basic Functions ===");
console.log();
// Simple function with no parameters
function sayHello() {
console.log(" Hello, World!");
}
console.log("Calling sayHello():");
sayHello();
console.log();
// Function with parameters
function greet(name) {
return "Hello, " + name + "!";
}
console.log("greet('Alice') → " + greet("Alice"));
console.log("greet('Bob') → " + greet("Bob"));
console.log();
console.log("=== Default Paramet
...Try It: Advanced Functions
Explore scope, static variables, closures, arrow functions, and named arguments
// Advanced PHP Functions
console.log("=== Variable Scope ===");
console.log();
let globalVar = "I'm global";
function testScope() {
// In PHP, global variables are NOT accessible inside functions
// You need: global $globalVar; or $GLOBALS['globalVar']
let localVar = "I'm local";
console.log(" Inside function: localVar = " + JSON.stringify(localVar));
console.log(" Inside function: globalVar requires 'global' keyword in PHP");
}
testScope();
console.log(" Outside funct
...⚠️ Common Mistakes
return give null. PHP won't warn you!global keyword.&$param only when you need to modify the original variable.📋 Quick Reference — PHP Functions
| Feature | Syntax | Since |
|---|---|---|
| Basic function | function name() {} | PHP 4 |
| Type hints | function f(int $x): string | PHP 7.0 |
| Nullable | ?string | PHP 7.1 |
| Arrow fn | fn($x) => $x * 2 | PHP 7.4 |
| Named args | f(name: 'Alice') | PHP 8.0 |
| Variadic | function f(int ...$nums) | PHP 5.6 |
🎉 Lesson Complete!
You've mastered PHP functions! Next, learn how to work with arrays and collections — PHP's most powerful data structure.
Sign up for free to track which lessons you've completed and get learning reminders.