I want to check if $model is an instance of class A, B or C, but not D. So I have an array like that:
$relevant_classes = [A, B, C];
I know I can check with instance of
if the model is in instance of those classes. But do I now have to loop over the array and ask for each single class, if the model is an instance of it?
I would rather want to do something like if(in_array($model, $relevant_classes))
that compares the class instance. Is that possible in PHP (Laravel)?
You can call get_class()
to get the name of the class, so your test would be...
$relevant_classes = [A::class, "B", C::class]; // use ::class or the class string
if(in_array(get_class($model), $relevant_classes))
You can use interfaces for this. Small example:
<?php
interface iA {
public function foo();
}
interface iB {
public function bar();
}
class A implements iA {
public function foo(){ echo 1; }
}
class B implements iA {
public function foo(){ echo 2; }
}
class C implements iB {
public function bar(){ echo 3; }
}
class D implements iA, iB {
public function foo(){ echo 4; }
public function bar(){ echo 5; }
}
$classes = [new A, new B, new C, new D];
foreach ($classes as $class) {
if ($class instanceof iA) {
$class->foo();
}
if ($class instanceof iB) {
$class->bar();
}
}
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