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.
π 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 (2016) you could leverage the variadic function syntax, but that only works if all arguments of the function are of the same type or if the variadic parameter is the last argument.
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 workWithFoos(ArrayOfFoo $foos, string $otherArgument) : void {
foreach ($foos as $foo) {
// etc.
}
}
$foos = new ArrayOfFoo();
$foos[] = new Foo();
$foos[] = new Foo();
workWithFoos($foos, 'foo');
If anyone has a better way to tackle this, feel free to enlighten me by leaving a comment.
π 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…
See: https://nickescobedo.com/1198/php-type-hinting-arrays-using-the-splat-operator
See: http://blog.programster.org/extremely-defensive-php (14:51)
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)