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

Sii*_*ipe 5 php arrays object

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

例如:在数组($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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

或者可能:

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');
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

cea*_*eak 5

使用数组过滤器:

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


Neo*_*dan 0

如果您使用数组(而不是对象)作为集合,那么除了检查数组项之外,您没有任何其他选择。