型演算子
instanceof
を使用して、
ある PHP 変数が特定の
クラス
のオブジェクトのインスタンスであるかどうかを調べます。
例1 クラスでの instanceof
の使用法
<?php
class MyClass
{
}
class NotMyClass
{
}
$a = new MyClass;
var_dump($a instanceof MyClass);
var_dump($a instanceof NotMyClass);
?>
上の例の出力は以下となります。
bool(true) bool(false)
instanceof
は、ある変数が
特定の親クラスを継承したクラスのオブジェクトのインスタンスであるかどうかを調べることもできます。
例2 継承したクラスでの instanceof
の使用法
<?php
class ParentClass
{
}
class MyClass extends ParentClass
{
}
$a = new MyClass;
var_dump($a instanceof MyClass);
var_dump($a instanceof ParentClass);
?>
上の例の出力は以下となります。
bool(true) bool(true)
あるオブジェクトが特定のクラスのインスタンスで ない
ことを調べるには、
論理 否定
演算子
を使用します。
例3 instanceof
を使用して、オブジェクトがクラスのインスタンスで ない
かどうかを調べる方法
<?php
class MyClass
{
}
$a = new MyClass;
var_dump(!($a instanceof stdClass));
?>
上の例の出力は以下となります。
bool(true)
最後に、instanceof
は、ある変数が特定の
インターフェイス
を実装したクラスのオブジェクトのインスタンスであるかどうかも調べることができます。
例4 インターフェイスでの instanceof
の使用法
<?php
interface MyInterface
{
}
class MyClass implements MyInterface
{
}
$a = new MyClass;
var_dump($a instanceof MyClass);
var_dump($a instanceof MyInterface);
?>
上の例の出力は以下となります。
bool(true) bool(true)
通常、instanceof
ではリテラルのクラス名を使用しますが、
別のオブジェクトや文字列変数を使用することもできます。
例5 変数を用いた instanceof
の使用法
<?php
interface MyInterface
{
}
class MyClass implements MyInterface
{
}
$a = new MyClass;
$b = new MyClass;
$c = 'MyClass';
$d = 'NotMyClass';
var_dump($a instanceof $b); // $b MyClass クラスのオブジェクトです
var_dump($a instanceof $c); // $c は文字列 'MyClass' です
var_dump($a instanceof $d); // $d は文字列 'NotMyClass' です
?>
上の例の出力は以下となります。
bool(true) bool(true) bool(false)
instanceof は、もし確かめる変数がオブジェクトでなくてもエラーになりません。単に
false
を返すだけです。ただし、PHP 7.3.0 以前では、定数を調べることはできませんでした。
例6 instanceof
での他の変数の調べかた
<?php
$a = 1;
$b = NULL;
$c = imagecreate(5, 5);
var_dump($a instanceof stdClass); // $a は配列です
var_dump($b instanceof stdClass); // $b は NULL です
var_dump($c instanceof stdClass); // $c はリソースです
var_dump(FALSE instanceof stdClass);
?>
上の例の出力は以下となります。
bool(false) bool(false) bool(false) PHP Fatal error: instanceof expects an object instance, constant given
PHP 7.3.0 以降では、
instanceof
の左辺値に定数を指定できるようになりました。
例7 instanceof
を使って定数を確認する
<?php
var_dump(FALSE instanceof stdClass);
?>
上の例の PHP 7.3 での出力は、このようになります。
bool(false)
PHP 8.0.0 以降では、
instanceof
は任意の式と一緒に使えるようになりました。
式は文字列を生成するもので、かつ括弧で囲む必要があります。
例8 instanceof
を任意の式と一緒に使う
<?php
class ClassA extends \stdClass {}
class ClassB extends \stdClass {}
class ClassC extends ClassB {}
class ClassD extends ClassA {}
function getSomeClass(): string
{
return ClassA::class;
}
var_dump(new ClassA instanceof ('std' . 'Class'));
var_dump(new ClassB instanceof ('Class' . 'B'));
var_dump(new ClassC instanceof ('Class' . 'A'));
var_dump(new ClassD instanceof (getSomeClass()));
?>
上の例の PHP 8 での出力は、このようになります。:
bool(true) bool(true) bool(false) bool(true)
instanceof
演算子は、is_a()
関数とは機能的に異なる部分があります。
User Contributed Notes 16 notes
Posting this so the word typeof appears on this page, so that this page will show up when you google 'php typeof'. ...yeah, former Java user.
Checking an object is not an instance of a class, example #3 uses extraneous parentheses.
<?php
var_dump(!($a instanceof stdClass));
?>
Because instanceof has higher operator precedence than ! you can just do
<?php
var_dump( ! $a instanceof stdClass );
?>
You are also able to compare 2 objects using instanceOf. In that case, instanceOf will compare the types of both objects. That is sometimes very useful:
<?php
class A { }
class B { }
$a = new A;
$b = new B;
$a2 = new A;
echo $a instanceOf $a; // true
echo $a instanceOf $b; // false
echo $a instanceOf $a2; // true
?>
I don't see any mention of "namespaces" on this page so I thought I would chime in. The instanceof operator takes FQCN as second operator when you pass it as string and not a simple class name. It will not resolve it even if you have a `use MyNamespace\Bar;` at the top level. Here is what I am trying to say:
## testinclude.php ##
<?php
namespace Bar1;
{
class Foo1{ }
}
namespace Bar2;
{
class Foo2{ }
}
?>
## test.php ##
<?php
include('testinclude.php');
use Bar1\Foo1 as Foo;
$foo1 = new Foo(); $className = 'Bar1\Foo1';
var_dump($foo1 instanceof Bar1\Foo1);
var_dump($foo1 instanceof $className);
$className = 'Foo';
var_dump($foo1 instanceof $className);
use Bar2\Foo2;
$foo2 = new Foo2(); $className = 'Bar2\Foo2';
var_dump($foo2 instanceof Bar2\Foo2);
var_dump($foo2 instanceof $className);
$className = 'Foo2';
var_dump($foo2 instanceof $className);
?>
## stdout ##
bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(false)
if you have only class names (not objects) you can use that snippet: https://3v4l.org/mUKUC
<?php
interface i{}
class a implements i{}
var_dump(a::class instanceof i); // false
var_dump(in_array(i::class, class_implements(a::class), true)); // true
Doing $a instanceof stdClass from inside a namespace will not work on its own.
You will have to do:
<?php
if ($a instanceof \stdClass)
?>
Example #5 could also be extended to include...
var_dump($a instanceof MyInterface);
The new result would be
bool(true)
So - instanceof is smart enough to know that a class that implements an interface is an instance of the interface, not just the class. I didn't see that point made clearly enough in the explanation at the top.
SIMPLE, CLEAN, CLEAR use of the instanceof OPERATOR
First, define a couple of simple PHP Objects to work on -- I'll introduce Circle and Point. Here's the class definitions for both:
<?php
class Circle
{
protected $radius = 1.0;
/*
* This function is the reason we are going to use the
* instanceof operator below.
*/
public function setRadius($r)
{
$this->radius = $r;
}
public function __toString()
{
return 'Circle [radius=' . $this->radius . ']';
}
}
class Point
{
protected $x = 0;
protected $y = 0;
/*
* This function is the reason we are going to use the
* instanceof operator below.
*/
public function setLocation($x, $y)
{
$this->x = $x;
$this->y = $y;
}
public function __toString()
{
return 'Point [x=' . $this->x . ', y=' . $this->y . ']';
}
}
?>
Now instantiate a few instances of these types. Note, I will put them in an array (collection) so we can iterate through them quickly.
<?php
$myCollection = array(123, 'abc', 'Hello World!',
new Circle(), new Circle(), new Circle(),
new Point(), new Point(), new Point());
$i = 0;
foreach($myCollection AS $item)
{
/*
* The setRadius() function is written in the Circle class
* definition above, so make sure $item is an instance of
* type Circle BEFORE calling it AND to avoid PHP PMS!
*/
if($item instanceof Circle)
{
$item->setRadius($i);
}
/*
* The setLocation() function is written in the Point class
* definition above, so make sure $item is an instance of
* type Point BEFORE calling it AND to stay out of the ER!
*/
if($item instanceof Point)
{
$item->setLocation($i, $i);
}
echo '$myCollection[' . $i++ . '] = ' . $item . '<br>';
}
?>
$myCollection[0] = 123
$myCollection[1] = abc
$myCollection[2] = Hello World!
$myCollection[3] = Circle [radius=3]
$myCollection[4] = Circle [radius=4]
$myCollection[5] = Circle [radius=5]
$myCollection[6] = Point [x=6, y=6]
$myCollection[7] = Point [x=7, y=7]
$myCollection[8] = Point [x=8, y=8]
You can use "self" to reference to the current class:
<?php
class myclass {
function mymethod($otherObject) {
if ($otherObject instanceof self) {
$otherObject->mymethod(null);
}
return 'works!';
}
}
$a = new myclass();
print $a->mymethod($a);
?>
If you want to use "$foo instanceof $bar" to determine if two objects are the same class, remember that "instanceof" will also evaluate to true if $foo is an instance of a _subclass_ of $bar's class.
If you really want to see if they are the _same_ class, then they both have to be instances of each other's class. That is:
<?php
($foo instanceof $bar && $bar instanceof $foo)
?>
Consider it an alternative to "get_class($bar) == get_class($foo)" that avoids the detour through to string lookups and comparisons.
If you want to test if a classname is an instance of a class, the instanceof operator won't work.
<?php
$classname = 'MyClass';
if( $classname instanceof MyParentClass) echo 'Child of it';
else echo 'Not child of it';
?>
Will always output
Not child of it
You must use a ReflectionClass :
<?php
$classname = 'MyClass';
$myReflection = new ReflectionClass($classname);
if( $myReflection->isSubclassOf('MyParentClass')) echo 'Child of it';
else echo 'Not child of it';
?>
Will output the good result.
If you're testing an interface, use implementsInterface() instead of isSublassOf().
Response to vinyanov at poczta dot onet dot pl:
You mentionned "the instanceof operator will not accept a string as its first operand". However, this behavior is absolutely right and therefore, you're misleading the meaning of an instance.
<?php 'ClassA' instanceof 'ClassB'; ?> means "the class named ClassA is an instance of the class named ClassB". This is a nonsense sentence because when you instanciate a class, you ALWAYS obtain an object. Consequently, you only can ask if an object is an instance of a class.
I believe asking if "a ClassA belongs to a ClassB" (or "a ClassA is a class of (type) ClassB") or even "a ClassA is (also) a ClassB" is more appropriate. But the first is not implemented and the second only works with objects, just like the instanceof operator.
Plus, I just have tested your code and it does absolutely NOT do the same as instanceof (extended to classes)! I can't advise anyone to reuse it. The use of <?php is_instance_of ($instanceOfA, 'ClassB'); ?> raises a warning "include_once(Object id #1.php) …" when using __autoload (trying to look for $instanceOfA as if it was a class name).
Finally, here is a fast (to me) sample function code to verify if an object or class:
<?php
function kind_of (&$object_or_class, $class)
{
return is_object ($object_or_class) ?
$object_or_class instanceof $class
: (is_subclass_of ($object_or_class $class)
|| strtolower ($object_or_class) == strtolower ($class));
}
?>
The PHP parser generates a parse error on either of the two lines that are commented out here.
Apparently the 'instanceof' construct will take a string variable in the second spot, but it will NOT take a string... lame
class Bar {}
$b = new Bar;
$b_class = "Bar";
var_export($b instanceof Bar); // this is ok
var_export($b instanceof $b_class); // this is ok
//var_export($f instanceof "Bar"); // this is syntactically illegal
//var_export($f instanceof 'Bar'); // this is syntactically illegal
Using an undefined variable will result in an error.
If variable is in doubt, one must prequalify:
if ( isset( $MyInstance ) and $MyInstance instanceof MyClass ) ...