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 you could leverage the variadic function syntax, but that only works if all arguments of the function are of the same type.

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 workWithFoo(ArrayOfFoo $foos, string $otherArgument) : void {
    foreach ($foos as $foo) {
        // etc.
    }
}

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

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.