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

SitePoint PHP Blog:
Creating Strictly Typed Arrays and Collections in PHP
Mar 27, 2017 @ 17:45:06

On the SitePoint PHP blog there's a new post from Bert Ramakers showing you how to create strictly typed arrays and collections in PHP.

One of the language features announced back in PHP 5.6 was the addition of the ... token to denote that a function or method accepts a variable length of arguments.

Something I rarely see mentioned is that it’s possible to combine this feature with type hints to essentially create typed arrays.

He starts with an example of a class/method that only takes in a certain type of objects as a collection (using the "...") with a fatal thrown if anything else is given. He also shows how to do the same thing with scalar types and the "..." operator with a typed input. He does point out one problem with this approach, namely that if more complex input is required the single type just wouldn't work. His solution involves custom collection classes where the settings are in the collection and not passed directly into the method. This collection then contains some of the base functionality (like getting an average value from a set of floats) and can be enhanced with other typical interfaces to work like any other collection. He also presents another option: using value objects for validation of the input.

tagged: collection array strict typing tutorial operator

Link: https://www.sitepoint.com/creating-strictly-typed-arrays-collections-php/


Trending Topics: