Typed Arrays in PHP

php-logo

Tim Bezhashvyly:

Typed arrays exist in PHP, at least to some degree. This wonderful feature sneaked in as a side-effect of variadic functions that were added to the language in PHP 5.6.

Turns out one can actually typehint the variadic parameter, as so:

<?php
function foo (Product ...$products)
{
     /* ... */
}

Only works if your function has one argument though (or if the “typed array” is the last parameter to your function). Otherwise you’ll get a Fatal Error Only the last parameter can be variadic

Typed Arrays in PHP →

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

1 Comment

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.