我想對在構造中迭代的數組表達式的鍵(如果是哈希)和值進行類型檢查foreach,例如:foreach ($reasons as AuthenticationResponse $reason)
...instanceof除了檢查循環體之外,還有其他選擇嗎?
1 回答

慕的地6264312
TA貢獻1817條經驗 獲得超6個贊
不,但這只是一行代碼,應該沒有問題。
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;
}
這將跳過所有非測試和輸出:
Test0
Test1
Test2
Test3
Test4
Test5
Test6
Test7
Test8
Test9
- 1 回答
- 0 關注
- 111 瀏覽
添加回答
舉報
0/150
提交
取消