gpt4 book ai didi

php - 如何检查数组是否是特定对象的集合?

转载 作者:行者123 更新时间:2023-12-04 20:48:48 26 4
gpt4 key购买 nike

在我的类(class)中,我有一个需要数组的方法,并且应该根据集合类型以不同的方式使用该数组。数组项应该是对象,我需要知道这些对象是哪个类实例。

例如:在数组($obj1, $obj2) 中,我需要检查这些对象的实例,它们是从哪个类创建的。

这里有一些代码:

public function convertDataToInsert($data)
{
if (is_array($data)) {
foreach ($data as $obj) {
if ($obj instanceof CriterioDigital) {
//Ok, an array of CriterioDigital
} elseif ($obj instanceof ArquivoDigital) {
//Ok, an array of ArquivoDigital
} else {
throw new \Exception('Invalid parameter');
}
break;
}
}

或者可能:
public function convertDataToInsert($data)
{
if (is_array($data)) {
$obj = $data[0];
if ($obj instanceof CriterioDigital) {
//Ok, an array of CriterioDigital
} elseif ($obj instanceof ArquivoDigital) {
//Ok, an array of ArquivoDigital
} else {
throw new \Exception('Invalid parameter');
}
}
}

我只需要检查这个数组的集合类型。我知道我可以迭代它,但是在 php 中有没有更好的方法来做到这一点?

最佳答案

使用数组过滤器:

if (count(array_filter($data, function ($entry) {
return !($entry instanceof CriterioDigital);
})) > 0) {
throw new \DomainException('an array of CriterioDigital must be provided');
}

关于php - 如何检查数组是否是特定对象的集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45353132/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com