Adopt today's PHP: strict types, arrow functions, the nullsafe operator, enums, and the match expression.
Open this lesson in KodokonModern PHP embraces typing. declare(strict_types=1), placed as the first statement of the file, disables implicit conversions: passing the string '10' to a float parameter throws a TypeError instead of being silently converted. Type parameters and return values: your errors surface early, in the right place, rather than three files later.
<?php
declare(strict_types=1);
function applyDiscount(
float $price,
float $rate = 0.1
): float {
return round($price * (1 - $rate), 2);
}
echo applyDiscount(49.99);
echo PHP_EOL;
echo applyDiscount(100.0, 0.25);Arrow functions fn condense anonymous functions of a single expression. A major advantage over classic closures: they automatically capture the variables of the parent scope, without a use clause. They shine with array_map() and array_filter().
<?php
declare(strict_types=1);
$prices = [12.5, 49.9, 8.0, 120.0];
$rate = 0.2;
$discounted = array_map(
fn (float $p): float => round($p * (1 - $rate), 2),
$prices
);
$affordable = array_filter(
$discounted,
fn (float $p): bool => $p < 50
);
print_r($affordable);The nullsafe operator ?-> short-circuits a call as soon as a link in the chain is null, instead of causing a fatal error. Combined with ??, it replaces pyramids of if statements with a single readable line.
<?php
declare(strict_types=1);
class Address
{
public function __construct(
public readonly string $city
) {
}
}
class User
{
public function __construct(
public readonly ?Address $address = null
) {
}
}
$alice = new User(new Address('Lyon'));
$bob = new User();
echo $alice->address?->city ?? 'Unknown city';
echo PHP_EOL;
echo $bob->address?->city ?? 'Unknown city';Enums give a real type to closed sets of values (statuses, roles): it becomes impossible to create a nonexistent status. And match is a clear improvement over switch: strict comparison, a result returned as a value, and an UnhandledMatchError if no case matches - a safeguard against oversights.
<?php
declare(strict_types=1);
enum OrderStatus: string
{
case Pending = 'pending';
case Shipped = 'shipped';
case Delivered = 'delivered';
public function label(): string
{
return match ($this) {
self::Pending => 'Pending',
self::Shipped => 'Shipped',
self::Delivered => 'Delivered',
};
}
}
$status = OrderStatus::from('shipped');
echo $status->label();