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

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

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

instanceof除了检查循环体之外,还有其他选择吗?



jeck猫
浏览 91回答 1
1回答

慕的地6264312

不,但这只是一行代码,应该没有问题。class Test {&nbsp; &nbsp; public int $number;}class Dummy {&nbsp; &nbsp; public int $number;}$tests = [];for($i = 0; $i < 10; $i++) {&nbsp; &nbsp; $test = new Test();&nbsp; &nbsp; $test->number = $i;&nbsp; &nbsp; $dummy = new Dummy();&nbsp; &nbsp; $dummy->number = $i;&nbsp; &nbsp; $tests[] = $test;&nbsp; &nbsp; $tests[] = $dummy;}foreach($tests as $test) {&nbsp; &nbsp; if(!$test instanceof Test) continue;&nbsp; &nbsp; echo get_class($test), $test->number, PHP_EOL;}这将跳过所有非测试和输出:Test0Test1Test2Test3Test4Test5Test6Test7Test8Test9
打开App,查看更多内容
随时随地看视频慕课网APP