iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PHP Functions

Define a function with function. PHP supports default parameters, type declarations, return types, variadics, named arguments, and first-class callables.

Basics

PHP
function greet(string $name = 'world'): string
{
    return "Hello, $name!";
}

echo greet();           // Hello, world!
echo greet('Ada');       // Hello, Ada!

Multiple parameters & named arguments

PHP
function reserve(string $name, int $table, string $time, int $party = 2): void
{
    echo "$party for $name at table $table at $time";
}

reserve(name: 'Ada', table: 7, time: '19:00');

Named arguments (8.0+) skip parameter order — handy for functions with many optional params.

Variadic functions

PHP
function average(float ...$nums): float
{
    return array_sum($nums) / count($nums);
}

echo average(2, 4, 6, 8);   // 5

Return type declarations

DeclarationMeans
: int / : stringMust return that type.
: ?stringString or null.
: voidReturns nothing.
: never (8.1+)Function doesn't return — always throws or exits.
: int|stringUnion types (8.0+).
: A&BIntersection types (8.1+).

First-class callable syntax (8.1+)

PHP
$shout = strtoupper(...);            // make a callable from a function name
echo $shout('hello');                 // HELLO

$pop = $stack->pop(...);              // works for methods too
Tip: Add declare(strict_types=1); at the top of files where you want PHP to refuse implicit casts. Saves a lot of subtle bugs.

Example

Example
<?php
function greet(string $name = 'world'): string {
    return "Hello, $name!";
}
echo greet(), PHP_EOL;
echo greet('Ada'), PHP_EOL;
Try it Yourself »

Exercise

Define a function with this keyword.

greet($name) {}

Test yourself

Q1. A function is declared with…
Q2. Named arguments arrived in…
Q3. First-class callable syntax is…

Discussion

Loading…