PHP Traversable的类型提示 [英] PHP Traversable type hint
问题描述
我的系统使用相对简单的功能的的foreach
I have a relatively simple function which uses a foreach
function foo($t) {
$result;
foreach($t as $val) {
$result = dosomething($result, $val);
}
return $result;
}
我想输入提示,并 Traverable
似乎是确切类型提示我需要
I would like to type hint, and Traverable
seems to be the exact type hint I need
function foo(Traversable $t) {
然而,这给出了一个使用数组(这是在的foreach
ofcourse使用)时, E_RECOVERABLE_ERROR
:<一HREF =http://phpfiddle.org/main/$c$c/xc1-arr>例如
However this gives a E_RECOVERABLE_ERROR
when using an array (which is ofcourse usable in a foreach
): example
Argument 1 passed to foo() must implement interface Traversable, array given
是否有输入提示的方式,或者这是不可能的?
Is there a way to type hint or is this not possible?
推荐答案
有一个关于此错误的:的#41942 。被标记为不是一个错误。由于PHP数组是不是对象,他们无法实现一个接口,这样一个没有办法输入暗示两者阵列
和 Traversable的
。
There is a bug about this: #41942. Closed as 'not a bug'. As PHP arrays are not objects they cannot implement an interface and a such there is no way to type hint both array
and Traversable
.
您可以使用 iterator_to_array
, ArrayIterator
或省略类型提示。需要注意的是iterator_to_array将整个迭代器复制到一个数组因此,一个可能是低效的。
You can use iterator_to_array
, ArrayIterator
or omit the type hint. Note that iterator_to_array will copy the whole iterator into an array an might thus be inefficient.
// These functions are functionally equivalent but do not all accept the same arguments
function foo(array $a) { foobar($a); }
function bar(Traversable $a) { foobar($a); }
function foobar($a) {
foreach($a as $key => $value) {
}
}
$array = array(1,2,3)
$traversable = new MyTraversableObject();
foo($array);
foo(iterator_to_array($traversable));
bar(new ArrayIterator($array));
bar($traversable);
foobar($array);
foobar($traversable);
这篇关于PHP Traversable的类型提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!