Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Typed Arrays in PHP
Feb 16, 2016 @ 09:36:29

On thePHP.cc site there's an article posted from Tim Bezhashvyly, a software engineer in Berlin, looking at typed arrays in PHP and how they (sort of) exist.

Even though Rasmus Lerdorf denies the fact, 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.

[...] An array comprising the full argument list can be obtained using the func_get_args() function. [...] Regardless how many arguments have been passed to the function above, they are all accessible as elements of the ?$args array. This is nothing special really, until you realize that variadics can be augmented with type declarations.

Using these type declarations, you can, in essence create "typed arrays" where you know the end result will only be a set of objects of the defined type. The same goes for scalar type handling in PHP 7, making it so you can use things like "string" or "int" as your type enforcement. He does point out two issues in using this method however: the limit PHP places on the number of variadics in the function definition and that using functions to enforce types could result in a fatal error.

tagged: typed array hinting enforcement tutorial variadics

Link: https://thephp.cc/news/2016/02/typed-arrays-in-php