Reputation: 3569
Is it possible to dertermine the elements type of the returning array in a function?
For example, if the elements should be floats:
class test{
/**
* This should return an array containing float values,
* but I get a fatal error instead
*/
public static function doStuff() : float[] {
return [ 10.3, 12.8 ];
}
}
Upvotes: 2
Views: 76
Reputation: 3016
Unfortunately you can't type-check the contents of an array like that.
If you really insist on doing this, you could create your own collection class that wraps around the array and ensures the type of its elements:
class FloatCollection
{
private $array = [];
public function __construct($array = [])
{
foreach ($array as $value) {
$this->add($value);
}
}
public function add(float $value)
{
$this->array[] = $value;
}
...
}
Then you can type check for that:
public static function doStuff() : FloatCollection
{
return new FloatCollection([10.3, 12.8]);
}
But it might be a lot of unnecessary work for what you're trying to achieve.
Upvotes: 2