Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Check if $model is instance of one out of many classes

Tags:

php

laravel

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)?

like image 947
molerat Avatar asked Sep 10 '25 21:09

molerat


2 Answers

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))
like image 182
Nigel Ren Avatar answered Sep 13 '25 10:09

Nigel Ren


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();
    }
}
like image 30
Eakethet Avatar answered Sep 13 '25 09:09

Eakethet