PHP 8.3 โ Features and Syntax Quick Reference
notereference1c3d
Markdown
PHP 8.3 โ Features and Syntax Quick Reference
New in PHP 8.3
| Feature | Example |
|---|---|
| Typed class constants | const string NAME = 'value'; |
json_validate() | Check JSON without decoding |
Randomizer additions | New random byte methods |
#[Override] attribute | Mark overridden methods |
| Deep clone readonly | Clone readonly properties |
PHP 8.x Features in Use
// Named arguments (8.0)
array_slice(array: $arr, offset: 2, length: 5);
// Match expression (8.0)
$result = match($status) {
'active' => 'Online',
'banned' => 'Blocked',
default => 'Unknown',
};
// Nullsafe operator (8.0)
$city = $user?->getAddress()?->getCity();
// Fibers (8.1)
$fiber = new Fiber(fn() => 'done');
// Enums (8.1)
enum Status: string {
case Active = 'active';
case Banned = 'banned';
}
// Readonly properties (8.1)
class User {
public function __construct(
public readonly int $id,
public readonly string $email,
) {}
}
// First class callables (8.1)
$fn = strlen(...);
// Intersection types (8.1)
function foo(Countable&Iterator $x) {}
// readonly classes (8.2)
readonly class Point {
public function __construct(
public float $x,
public float $y,
) {}
}
Common Patterns
// Strict types (always use)
declare(strict_types=1);
// Type-safe DB value
$id = (int) DB::value("SELECT id FROM ...");
// Null coalescing
$name = $_POST['name'] ?? 'default';
// Spread operator
$merged = [...$arr1, ...$arr2];
// Array destructuring
[$first, $second] = $array;
[, $second] = $array; // skip first
// Short closure
$double = fn($x) => $x * 2;