1
votes

So my understanding is I can not type hint multiple objects that may be passed to a class. So i figured i could leverage the reflection api to figure this out. maybe its bad practice in general but it is what it is. anyway, here is basically my layout. Without using reflection class, are there any ways of type hinting multiple classes? is this a good way of handling this situation?

interface Power { }

class mPower implements Power { }

class cPower implements Power { }

class Model extends ApiModel {

    function __construct(stdClass $powerObj) {

         $po = new ReflectionClass($powerObj);      
         if ( in_array('Power', $po->getInterfaceNames()))  {
            // do something
         }

    }
}
3
out can type hint on an interface function __construct(Power $powerObj)Orangepill

3 Answers

2
votes

How about the instanceof operator http://php.net/manual/en/language.operators.type.php

function __construct($powerObj) {
    if($powerObj instanceof Power) {
        //Do stuff
    }
}

Also, since everything is sharing a common interface. You can typehint that:

function __construct(Power $powerObj) {
        //Do stuff
}
1
votes

You can do type hinting on an interface though... in your example

function __construct(Power $powerObj) {

}
0
votes

You can use is_a() for this. No need for reflection at all. is_a() works for to check for parent classes of an object as well as implemented interfaces:

interface A {
}

class B implements A {
}


$b = new B();
var_dump(is_a($b, 'A')); // bool(true)