繁体   English   中英

在“foreach”构造中键入检查键或值的最佳方法?

[英]Best way to typecheck key or value in 'foreach' construct?

我想对在foreach构造中迭代的数组表达式的键(如果是哈希)和值进行类型检查,例如:

foreach ($reasons as AuthenticationResponse $reason)
...

是否有任何替代方法可以在循环体中将其作为instanceof检查?

不,但这只是一行代码,应该没有任何问题。

class Test {
    public int $number;
}

class Dummy {
    public int $number;
}

$tests = [];

for($i = 0; $i < 10; $i++) {
    $test = new Test();
    $test->number = $i;
    $dummy = new Dummy();
    $dummy->number = $i;
    $tests[] = $test;
    $tests[] = $dummy;
}

foreach($tests as $test) {
    if(!$test instanceof Test) continue;
    echo get_class($test), $test->number, PHP_EOL;
}

这将跳过所有非测试和 output:

Test0
Test1
Test2
Test3
Test4
Test5
Test6
Test7
Test8
Test9

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM