$array = [
[
FirstClass,
SecondClass,
ThirdClass,
],
[
ThirdClass,
MaxClass
],
[
FirstClass,
ThirdClass
],
[
SecondClass,
FirstClass,
]
];
我想检查MaxClass是否存在,如果有多个则另外抛出错误.
所以我这样做:
foreach ($array as $class) {
if (get_class($class) == 'MaxClass') {
//different operations
}
}
检查我正在添加:
$count = 0;
foreach ($array as $class) {
if (get_class($class) == 'MaxClass') {
if ($count < 2) {
//different operations
} else {
throw new Exception('Too many MaxClass!');
}
}
}
但也许比使用变量$count更好的方法?
第二个问题 – 我应该使用什么异常类?也许RuntimeException?
解决方法:
class ReachedMaxLimitException extends LogicException {}
$count = array_reduce(
call_user_func_array('array_merge', $array), // flatten array
function ($count, $o) { return $count + ($o instanceof MaxClass); },
0
);
if ($count > 1) {
raise new ReachedMaxLimitException;
}
显然,将理智检查与“//不同的操作”分开,但这也正是重点.