Reading — step 1 of 5
Learn
~1 min readFunctions
Functions use the function keyword. Type declarations (since 7.0+ for params, 7.1+ for returns) are optional but highly recommended:
function square(int $n): int {
return $n * $n;
}
function greet(string $name, string $greeting = "Hello"): string {
return "$greeting, $name!";
}
echo square(5); // 25
echo greet("Alice"); // Hello, Alice!
echo greet("Bob", "Howdy"); // Howdy, Bob!
Functions are case-insensitive (legacy quirk — call Square(5) and it works). Function names live in their own global namespace.
Add declare(strict_types=1); at the top of a file to make type declarations strict — passing a wrong type becomes a TypeError instead of a silent coerce. Recommended for new code.
Variadic params with ...: function sum(...$nums) { return array_sum($nums); }.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…