PHP
<?php
function greet(string $name): string
{
return "Namaste, $name!";
}
echo greet("Sita"); // Namaste, Sita!Default parameters
PHP
<?php
function greet(string $name, string $greeting = "Namaste"): string
{
return "$greeting, $name!";
}
echo greet("Ram"); // Namaste, Ram!
echo greet("Ram", "Hello"); // Hello, Ram!Parameters with defaults must come after those without.
Named arguments (PHP 8+)
Skip optional parameters by naming the one you want:
PHP
<?php
function makeCoffee(string $type = 'latte', int $sugar = 1, bool $hot = true) { }
makeCoffee(hot: false); // only override the last one
makeCoffee(type: 'espresso', sugar: 0);Type declarations
Declaring types catches mistakes early and documents intent:
PHP
<?php
function total(float $price, int $qty): float
{
return $price * $qty;
}Add declare(strict_types=1); as the first line of a file to make
PHP reject wrong types instead of silently converting them:
PHP
<?php
declare(strict_types=1);
function double(int $n): int { return $n * 2; }
double("5"); // TypeError — without strict_types this would return 10Turning this on in every new file is one of the highest-value habits in modern PHP.
Nullable and union types
PHP
<?php
function findUser(int $id): ?array // array or null
{
return $id === 1 ? ['name' => 'Sita'] : null;
}
function format(int|float $n): string // union type (PHP 8+)
{
return number_format($n, 2);
}Passing by reference
Normally arguments are copies. Prefix with & to let the function modify
the caller's variable:
PHP
<?php
function addOne(int &$n): void
{
$n++;
}
$count = 5;
addOne($count);
echo $count; // 6Use this sparingly — functions that return values are easier to reason about than functions that mutate their inputs.
Variable-length arguments
PHP
<?php
function sum(int ...$numbers): int
{
return array_sum($numbers);
}
echo sum(1, 2, 3, 4); // 10Arrow functions
Short, single-expression closures that capture outer variables automatically:
PHP
<?php
$rate = 1.13;
$withVat = array_map(fn($p) => $p * $rate, [100, 200]);
// [113, 226]