tech · 03 Dec 2020

PHP Design Changes Through Its 7's Versions

Aleksandr Denisyuk

Aleksandr Denisyuk

PHP Developer

php 7 what's new
Illustration by Amir Kerr

Let's review the features that have changed PHP design throughout its 7’s versions. Here is a key features cheat sheet to help you refactor code in your packages or projects.

PHP 7.0

1. Added ?? null coalescing operator

2. Classes, functions, and constants being imported from the same namespace can now be grouped together in a single-use statement:

use namespace\{Foo, Bar as B};
use const namespace\{Foo, Bar};
use function namespace\{foo, bar};

3. Scalar types bool, float, int, string in signatures

4. Added strict mode to types in signatures:

declare(strict_types=1);

5. Class member access on cloning has been added:

(clone $foo)->bar();

6. Support for anonymous classes has been added via new class. These can be used in place of full class definitions for throwaway objects:

new class {
    // ...
};

7. Added <=> spaceship operator for comparing two expressions:

1 <=> 1; // 0
2 <=> 3; // -1
3 <=> 2; // 1

8. Array constants can now be defined with define():

define('ANIMALS', [
    'Cat',
    'Lion',
    'Panther',
]);

ANIMALS[1]; // Lion

9. Many fatal and recoverable fatal errors have been converted to exceptions. These error exceptions inherit from the Error class, which itself implements the Throwable interface (the new base interface all exceptions inherit):

.Throwable
├── Error
│   ├── ArithmeticError
│   ├── AssertionError
│   ├── DivisionByZeroError
│   ├── ParseError
│   ├── TypeError
└── Exception
    ├── ErrorException
    ├── LogicException
    │   ├── BadFunctionCallException
    │   │   └── BadMethodCallException
    │   ├── DomainException
    │   ├── InvalidArgumentException
    │   ├── LengthException
    │   └── OutOfRangeException
    └── RuntimeException
        ├── OutOfBoundsException
        ├── OverflowException
        ├── RangeException
        ├── UnderflowException
        └── UnexceptedValueException

PHP 7.1

1. Support for specifying the visibility of class constants has been added:

class Foo
{
    private const FOO = 'foo';
    protected const BAR = 'bar';
    public const XYZ = 'xyz';
}

2. Negative string and array offsets are now also supported in the simple variable parsing syntax inside of strings:

$str = 'foobar';

$str[-1]; // r

3. Added void, iterable pseudo-types

4. Multiple exceptions per catch block may now be specified using the pipe character |. This is useful for when different exceptions from different class hierarchies are handled in the same way:

try {
    // ...
} catch (
    \DomainException
    | \LogicException $e
) {
    // ...
}

5. Added ArgumentCountError exception

6. Type declarations for parameters and return values can now be marked as nullable by prefixing the type name with a question mark. This means that just like the specified type, null can be passed as an argument, or returned as a value, respectively:

function foobar(): ?string {
    // ...
}

7. Added is_iterable() function

PHP 7.2

1. Added object pseudo-type

2. A trailing comma can now be added to the group-use syntax:

use Foo\Bar\{
    Foo,
    Bar,
};

3. Added is_countable() function

PHP 7.3

1. Added CompileError exception

2. Trailing commas in function and method calls are now allowed:

$compacted = compact(
    'posts',
    'units',
);

3. Trailing commas in function and method calls are now allowed, it's not possible in function definitions:

$data = [
    'foo' => '...',
    'bar' => '...',
];

array_key_first($data); // foo
array_key_last($data); // bar

4. A new flag has been added, JSON_THROW_ON_ERROR, which can be used with json_decode() or json_encode() and causes these functions to throw the new JsonException upon an error:

try {
    json_encode('{', JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
    // ...
}

PHP 7.4

1. Class properties now support type declarations:

class User
{
    public int $id;
    public string $name;
}

2. Arrow functions provide a shorthand syntax for defining functions with implicit by-value scope binding:

$factor = 10;

array_map(fn($n) => $n * $factor, [1, 2, 3]);

// [10, 20, 30]

3. Added ??= null coalescing assignment operator

4. Added unpacking inside arrays:

$parts = ['cat', 'lion'];

$data = ['jaguar', ...$parts, 'panther'];

// ['jaguar', 'cat', 'lion', 'panther'];

5. Numeric literals can contain underscores between digits:

1_000_000;

6. Throwing exceptions from __toString() is now permitted:

class Foo
{
    public function __toString()
    {
        throw new \Exception();
    }
}

7. Added magic methods __serialize() and __unserialize()

8. Added WeakReference class

Rate this article!

(15 ratings, average: 5 out of 5)