PHP, Programming

PHP Type Hinting Arrays Using The Splat Operator

It’s possible to type hint an array (sort of) in PHP without using a Doc block.

Version 5.6 added a splat operator or sometimes called argument unpacking. A splat operator is 3 dots before a parameter. The splat operator allows a user to pass in an arbitrary amount of parameters. The arbitrary parameters are then turned into an array by PHP.

For example if we have a method that adds items to a cart and expects each item added to the cart is an instance of CartItem we can do the following:

function addItemsToCart(CartItem ...$cartItems) {
    //$cartItems is an array of CartItem objects
}

$cartItem1 = new CartItem();
$cartItem2 = new CartItem();
$cartItem3 = new CartItem();

addItemsToCart($cartItem1, $cartItem2, $cartItem3);

The function can now be called using 1 or many CartItem parameters. The end result is $cartItems contains an array of CartItem objects.

Notice how we just pass as many parameters as we want to the function and the splat operator handles the rest. We could pass in 5 or 100 and the result would still be an array of CartItem objects. The splat operator allows someone to pass in an arbitrary amount of parameters to a function turning those parameters into an array.

Pros

  • IDEs can identify the type hint which helps auto completion and preventing simple mistakes.
  • Other developers reading the code can quickly identify what type is expected to be passed in.
  • PHP will throw an error if someone tries to pass something else besides a CartItem object.

Cons (maybe)

  • When using splat operator the splat parameter must be last. This is because it allows an arbitrary amount of parameters.
  • Other developers may not be familiar with the splat operator, but a quick look at PHP documentation may help.
Share this Story
Load More Related Articles
Load More By Nick Escobedo
Load More In PHP

Check Also

Intro to Laravel Context with Practical Examples