Reputation: 4191
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
}
}
}
Upvotes: 1
Views: 383
Reputation: 158060
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)
Upvotes: 0
Reputation: 24645
You can do type hinting on an interface though... in your example
function __construct(Power $powerObj) {
}
Upvotes: 1
Reputation: 43730
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
}
Upvotes: 2