In my class I have a method which expects as array, and this array should be used differently depending on the collection type. The array items should be objects, and I need to know which class instance these objects are.
For example: in the array($obj1, $obj2), I need to check the instance of these objects, which class they were created from.
Here some code:
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;
}
}
Or maybe:
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');
}
}
}
I only need to check the collection type of this array. I know I can iterate it, but is there any better way in php to do so?
Use an array filter :
if (count(array_filter($data, function ($entry) {
return !($entry instanceof CriterioDigital);
})) > 0) {
throw new \DomainException('an array of CriterioDigital must be provided');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With