is_a和instanceof有什么区别? [英] What is the difference between is_a and instanceof?
问题描述
我知道 instanceof
是一个运算符,并且 is_a
是一种方法.
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?
推荐答案
更新
自is_a()
的功能已更改.以下原始答案指出,is_a()
必须接受Object
作为第一个参数,但是PHP版本> = 5.3.9现在接受可选的第三个布尔参数$allow_string
(默认为
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);
instanceof
和is_a()
之间的新行为的主要区别在于,instanceof
将始终检查目标是否是指定类(包括扩展类)的实例化对象,而is_a()
仅要求$allow_string
参数设置为默认值false
时,将实例化该对象.
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
.
原始
实际上,is_a
是一个函数,而instanceof
是一种语言构造. is_a
会慢得多(因为它具有执行函数调用的所有开销),但是在任何一种方法中,总的执行时间都非常短.
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.
从5.3版开始不再使用,因此不必担心.
It's no longer deprecated as of 5.3, so there's no worry there.
但是有一个区别. is_a
作为函数将一个对象作为参数1,并将一个字符串(变量,常量或文字)作为参数2.所以:
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
将对象作为参数1,并且可以将类名(变量),对象实例(变量)或类标识符(类名(不带引号写成))作为参数2.
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
这篇关于is_a和instanceof有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!