In Doctrine's source code if stumbled upon the following test:
if (in_array('Doctrine\Common\Collections\Collection', class_implements($var))) {
// ...
}
I don't get why not using instanceof
instead:
if ($var instanceof Doctrine\Common\Collections\Collection) {
// ...
}
which is better in many ways.
Is there a tangible reason for doing this?
Maybe performances? But really, is there any real difference here, it seems to me it would be like simple VS double quotes.
By definition, class_implements
refers specifically to interfaces
where instanceof
refers to the class itself and all of its parents. In the example you provided, the code is verifying the implementation of an interface, and using instanceof
could cause unwanted results.
From the PHP Manual instanceof
instanceof is used to determine whether a PHP variable is an instantiated object of a certain class:
instanceof can also be used to determine whether a variable is an instantiated object of a class that inherits from a parent class:
Lastly, instanceof can also be used to determine whether a variable is an instantiated object of a class that implements an interface:
From the PHP Manual class_implements
class_implements — Return the interfaces which are implemented by the given class
class_implements
will return an array of all the interfaces that are implemented by a specified class.
One reason to use class_implements
over instanceof
is that you can use class_implements
on a string that is the name of a class:
<?php
interface HasTest {
public function test();
}
class TestClass implements HasTest {
public function test() {
return 'This is a quick test';
}
}
$test = array (
'test' => 'TestClass'
);
// !! Using instanceof
var_dump($test['test'] instanceof HasTest);
// !! Using class_implements
var_dump(in_array('HasTest', class_implements($test['test'])));
/**
* Output:
*
* bool(false)
* bool(true)
*/
$class = new $test['test'];
var_dump($class instanceof HasTest);
/**
* Output:
* bool(true)
*/
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