doudoulb1234 2010-06-10 19:19
浏览 41
已采纳

is_a和instanceof有什么区别?

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条回答 默认 最新

  • doucheng9634 2010-06-10 19:26
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(8条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么