What’s new in the upcoming PHP 7.4?

Good overview by Brent on the new features that will be landing in PHP 7.4, which is due somewhere December 2019.

I’m especially looking forward to Typed properties.

New in PHP 7.4 →

πŸ’­ One thing I personally find missing in PHP’s typehinting, is a way to typehint array contents β€” e.g. β€œI’d like an array of Foo‘s”. As posted before (2016) you could leverage the variadic function syntax, but that only works if all arguments of the function are of the same type or if the variadic parameter is the last argument.

The addition of a [] suffix on the hinted type – like Java has – could potentially solve this all:

// ⚠️ Fictional syntax! Does not work
function workWithFoo(Foo[] $foos, string $otherArgument) : void {
    foreach ($foos as $foo) {
        // etc.
    }
}

In the mean time I resort to hackery like this (src):

// Definition
class ArrayOfFoo extends \ArrayObject {
    public function offsetSet($key, $val) {
        if ($val instanceof Foo) {
            return parent::offsetSet($key, $val);
        }
        throw new \InvalidArgumentException('Value must be a Foo');
    }
}

// Usage
function workWithFoos(ArrayOfFoo $foos, string $otherArgument) : void {
    foreach ($foos as $foo) {
        // etc.
    }
}

$foos = new ArrayOfFoo();
$foos[] = new Foo();
$foos[] = new Foo();
workWithFoos($foos, 'foo');

If anyone has a better way to tackle this, feel free to enlighten me by leaving a comment.

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Join the Conversation

2 Comments

  1. πŸ‘‹ You’ve probably heard about the splat operator hack to do something similar with array validation? It’s not something I usually use but seen others use it frequently…

    public function addItemsToCart(CartItem ...$cartItems) {
        //$cartItems is an array of CartItem objects
    }
    
    $cartItem1 = new CartItem();
    $cartItem2 = new CartItem();
    $cartItem3 = new CartItem();
    
    addItemsToCart($cartItem1, $cartItem2, $cartItem3);
    

    See: https://nickescobedo.com/1198/php-type-hinting-arrays-using-the-splat-operator
    See: http://blog.programster.org/extremely-defensive-php (14:51)

    1. Yes. See the note that reads β€œAs posted before you could leverage the variadic function syntax, but that only works if all arguments of the function are of the same type” πŸ˜‰

      (emphasis added)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.