Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usefulness of using class_implements VS instanceof

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.

like image 650
Matthieu Napoli Avatar asked Jul 15 '13 19:07

Matthieu Napoli


2 Answers

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

like image 89
user20232359723568423357842364 Avatar answered Sep 23 '22 11:09

user20232359723568423357842364


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)
 */
like image 42
Tim Groeneveld Avatar answered Sep 24 '22 11:09

Tim Groeneveld