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?
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?
instanceof can be used with other object instances, the class's name, or an interface. I don't think that is_a() works with interfaces (only a string representing a class name), but correct me if it does.
Example from php.net:
interface MyInterface
{
}
class MyClass implements MyInterface
{
}
$a = new MyClass;
$b = new MyClass;
$c = 'MyClass';
$d = 'NotMyClass';
var_dump($a instanceof $b); // $b is an object of class MyClass
var_dump($a instanceof $c); // $c is a string 'MyClass'
var_dump($a instanceof $d); // $d is a string 'NotMyClass'
outputs:
bool(true)
bool(true)
bool(false)
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 as parameter 2. instanceof can take either a string as parameter, object, or an identifier (class name written without quotes).
I can't speak for performance -- I haven't measured anything yet -- but depending on what you are attempting, there are limitations with instanceof. Check out my question, just recently, about it:
http://stackoverflow.com/questions/3002594/php-instanceof-failing-with-class-constant
I've ended up using is_a instead. I like the structure of instanceof better (I think it reads nicer) and will continue to use it where I can.
In regards to ChrisF's answer, is_a() is no longer deprecated as of PHP 5.3.0. I find it's always safer to go by the official source for things like this.
With regards to your question, Daniel, I can't say about the performance differences, but part of it will come down to readibility and which you find easier to work with.
Also, there is some discussion about the confusion around negating an instanceof check vs is_a(). For example, for instanceof you would do:
<?php
if( !($a instanceof A) ) { //... }
?>
vs the following for is_a():
<?php
if( !is_a($a, 'A' ) { //... }
?>
or
<?php
if( is_a($a, 'A') === FALSE) { //... }
?>
Edit Looks like ChrisF deleted his answer, but the first part of my answer still stands.