20 Essential PHP 8 Features You Must Master in 2023

Discover the 20 most important PHP 8 features released by 2023, including string helpers, type utilities, new functions, JIT compilation, and syntax enhancements, each illustrated with clear code examples to help developers quickly adopt and leverage these improvements in their projects.

21CTO
21CTO
21CTO
20 Essential PHP 8 Features You Must Master in 2023

PHP continues to evolve, and keeping up with its latest capabilities is essential for developers. The following 20 PHP 8 features, introduced up to 2023, are presented with concise explanations and code examples.

1. str_contains()

Checks whether a string contains a given substring.

$sentence = "The quick brown 🦊 jumps over the lazy 🐶.";
$word = "🦊";
if (str_contains($sentence, $word)) {
    echo "The sentence contains 🦊.";
}

2. str_starts_with()

Determines if a string starts with a specified prefix.

$sentence = "🚀 Launch to space!";
if (str_starts_with($sentence, "🚀")) {
    echo "The sentence starts with a rocket emoji!";
}

3. str_ends_with()

Determines if a string ends with a specified suffix.

$sentence = "What a beautiful day!☀️";
if (str_ends_with($sentence, "☀️")) {
    echo "The sentence ends with a sun emoji!";
}

4. get_debug_type()

Returns the type name of a variable.

$num = 42;
echo get_debug_type($num); // "int"

5. get_resource_id()

Returns the unique identifier (handle) of a resource.

$file = fopen('test.txt', 'r');
echo get_resource_id($file); // e.g., "7"

6. fdiv()

A division function that supports division by zero without raising a warning.

$result = fdiv(10, 0);

7. preg_last_error_msg()

Provides a human‑readable message for the last PCRE error.

preg_match('/(/', '');
echo preg_last_error_msg(); // "missing )"

8. array_key_first()

Retrieves the first key of an array.

$array = ['🍏' => 'Apple', '🍊' => 'Orange', '🍇' => 'Grape'];
echo array_key_first($array); // "🍏"

9. array_key_last()

Retrieves the last key of an array.

$array = ['🍏' => 'Apple', '🍊' => 'Orange', '🍇' => 'Grape'];
echo array_key_last($array); // "🍇"

10. ErrorException::getSeverity()

Gets the severity level of an error.

try {
    trigger_error("Custom warning", E_USER_WARNING);
} catch (ErrorException $e) {
    echo $e->getSeverity(); // 512
}

11. Filter Functions (filter_var)

PHP 8 adds new filter capabilities; example using FILTER_VALIDATE_BOOL.

var_dump(filter_var('yes', FILTER_VALIDATE_BOOL)); // bool(true)

12. WeakMap

A class that holds object references without preventing their garbage collection.

$weakmap = new WeakMap();
$obj = new stdClass();
$weakmap[$obj] = 'Hello, world!';

13. Constructor Property Promotion (Value Objects)

Allows declaring and initializing properties directly in the constructor signature.

class Money {
    public function __construct(public int $amount, public string $currency) {}
}
$tenDollars = new Money(10, 'USD');

14. match Expression

A switch‑like expression that returns a value.

echo match (1) {
    0 => '🚫',
    1 => '✅',
    default => '⁉️',
};

15. Nullsafe Operator (?->)

Safely accesses properties or methods on potentially null values.

class User {
    public function getAddress(): ?Address { /* ... */ }
}
$user = new User();
$country = $user?->getAddress()?->country; // no error if getAddress() returns null

16. Named Arguments

Pass arguments to a function by specifying parameter names.

new Money(amount: 10, currency: 'USD');

17. Attributes (Annotations)

Metadata that can be attached to classes, methods, etc.

#[Attribute]
class ExampleAttribute {}

#[ExampleAttribute]
class ExampleClass {}

18. Constructor Property Promotion (Repeated for Emphasis)

Combines property declaration and constructor assignment in a single statement.

class Money {
    public function __construct(public int $amount, public string $currency) {}
}

19. Union Types

Allows a parameter or return type to accept multiple types.

function print_id(int|string $id): void {
    echo 'ID: ' . $id;
}

20. JIT Compilation

PHP 8 introduces two JIT engines—Tracing JIT and Function JIT—that can dramatically improve performance, though they cannot be demonstrated with a short code snippet.

Overall, PHP remains a rapidly evolving language with many exciting new features and improvements. Whether you are an experienced PHP developer or just starting out, investing time to understand and apply these features will make your code more modern, efficient, and maintainable.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

programmingNew Featurescode-examplesPHP8
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.