Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

php - What is the difference between is_a and 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...