What is the difference between is_a and instanceof?

后端 未结 9 911
难免孤独
难免孤独 2020-12-04 07:23

I am aware that instanceof is an operator and that is_a is a method.

Is the method slower in performance? What would you prefer to use?

9条回答
  •  攒了一身酷
    2020-12-04 07:48

    Update

    As of PHP 5.3.9, the functionality of is_a() has changed. The original answer below states that is_a() must accept an Object as the first argument, but PHP versions >= 5.3.9 now accept an optional third boolean argument $allow_string (defaults to false) to allow comparisons of string class names instead:

    class MyBaseClass {}
    class MyExtendingClass extends MyBaseClass {}
    
    // Original behavior, evaluates to false.
    is_a(MyExtendingClass::class, MyBaseClass::class);
    
    // New behavior, evaluates to true.
    is_a(MyExtendingClass::class, MyBaseClass::class, true);
    

    The key difference in the new behavior between instanceof and is_a() is that instanceof will always check that the target is an instantiated object of the specified class (including extending classes), whereas is_a() only requires that the object be instantiated when the $allow_string argument is set to the default value of false.


    Original

    Actually, is_a is a function, whereas instanceof is a language construct. is_a will be significantly slower (since it has all the overhead of executing a function call), but the overall execution time is minimal in either method.

    It's no longer deprecated as of 5.3, so there's no worry there.

    There is one difference however. is_a being a function takes an object as parameter 1, and a string (variable, constant, or literal) as parameter 2. So:

    is_a($object, $string); // <- Only way to call it
    

    instanceof takes an object as parameter 1, and can take a class name (variable), object instance (variable), or class identifier (class name written without quotes) as parameter 2.

    $object instanceof $string;      // <- string class name
    $object instanceof $otherObject; // <- object instance
    $object instanceof ClassName;    // <- identifier for the class
    

提交回复
热议问题