20 PHP Features You Should Know in 2023

PHP is always evolving, and it’s important to stay up-to-date with the latest features and improvements. This article introduces 20 PHP features you should know as of 2023, each illustrated with a handy code example.

1. str_contains():

Checks if a string is contained in another string.

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

2. str_starts_with():

Checks if a string starts with a given substring.

$sentence = "πŸš€ Launching into space!";
if (str_starts_with($sentence, "πŸš€")) {
    echo "The sentence starts with a rocket emoji!";
}

3. str_ends_with():

Checks if a string ends with a given substring.

$sentence = "It's a beautiful day! β˜€οΈ";
if (str_ends_with($sentence, "β˜€οΈ")) {
    echo "The sentence ends with a sun emoji!";
}

4. get_debug_type():

Gets the type of a variable.

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

5. get_resource_id():

Returns the unique identifier of the given resource.

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

6. fdiv():

Division function that includes support for dividing by zero.

$result = fdiv(10, 0); // INF

7. preg_last_error_msg():

Returns a human-readable message for the last PCRE regex execution error.

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

8. array_key_first():

Fetches the first key of an array.

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

9. array_key_last():

Fetches the last key of an array.

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

10. ErrorException::getSeverity():

Gets the severity of the error.

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

11. Filter Functions:

PHP 8 introduced several new filter functions. Here’s an example using filter_var with FILTER_VALIDATE_BOOL:

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

12. Weak Map:

A new class that holds references to objects, which does not prevent those objects from being garbage collected.

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

13. Value Objects:

PHP 8 introduced Constructor Property Promotion, a new syntax for constructing value objects.

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

$tenDollars = new Money(10, 'USD');

14. Match Expression:

This is a switch-like statement.

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

15. Nullsafe Operator:

This new operator (?->) allows null checking when accessing properties or methods.

class User {
    public function getAddress(): ?Address {
        // returns Address or null
    }
}

$user = new User();
$country = $user?->getAddress()?->country; // no error if getAddress() returns null

16. Named Arguments:

This feature allows you to pass in values to a function by specifying the value name.

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

17. Attributes:

Also known as annotations in other programming languages.

#[Attribute]
class ExampleAttribute {}

#[ExampleAttribute]
class ExampleClass {}

18. Constructor Property Promotion:

This feature allows the combination of class properties and the constructor into a single declaration.

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

19. Union Types:

This feature allows for type declarations that can be one of multiple types.

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

20. Just In Time Compilation (JIT):

PHP 8 introduces two JIT compilation engines, Tracing JIT and Function JIT.

Note: JIT compilation isn’t a feature you can directly demonstrate with a code snippet, but it’s an important improvement in PHP 8 that can provide significant performance improvements.

Source : https://medium.com/@berastis/20-php-features-you-should-know-in-2023-18d9879f36f2

Leave a Reply