instanceof(型別運算子)

為了檢查某個物件是否屬於某個類,從 PHP 版本 5 開始,可以使用(二進位制)instanceof 運算子。

第一個(左)引數是要測試的物件。如果此變數不是物件,則 instanceof 始終返回 false。如果使用常量表示式,則會引發錯誤。

第二個(右)引數是要比較的類。該類可以作為類名本身提供,包含類名(不是字串常量!)的字串變數或該類的物件。

class MyClass {
}

$o1 = new MyClass();
$o2 = new MyClass();
$name = 'MyClass';

// in the cases below, $a gets boolean value true
$a = $o1 instanceof MyClass;
$a = $o1 instanceof $name;
$a = $o1 instanceof $o2;

// counter examples:
$b = 'b';
$a = $o1 instanceof 'MyClass'; // parse error: constant not allowed
$a = false instanceof MyClass; // fatal error: constant not allowed
$a = $b instanceof MyClass;    // false ($b is not an object)

instanceof 還可以用於檢查物件是否屬於擴充套件另一個類或實現某個介面的某個類:

interface MyInterface {
}

class MySuperClass implements MyInterface {
}

class MySubClass extends MySuperClass {
}

$o = new MySubClass();

// in the cases below, $a gets boolean value true    
$a = $o instanceof MySubClass;
$a = $o instanceof MySuperClass;
$a = $o instanceof MyInterface;

要檢查的物件是否是一些類的,未操作者(!)可用於:

class MyClass {
}

class OtherClass {
}

$o = new MyClass();
$a = !$o instanceof OtherClass; // true

請注意,不需要 $o instanceof MyClass 周圍的括號,因為 instanceof 的優先順序高於 !,儘管它可以使程式碼括號中更易讀。

注意事項

如果某個類不存在,則呼叫已註冊的自動載入函式以嘗試定義該類(這是文件本部分範圍之外的主題!)。在 5.1.0 之前的 PHP 版本中,instanceof 運算子也會觸發這些呼叫,從而實際定義類(如果無法定義類,則會發生致命錯誤)。要避免這種情況,請使用字串:

// only PHP versions before 5.1.0!
class MyClass {
}

$o = new MyClass();
$a = $o instanceof OtherClass; // OtherClass is not defined!
// if OtherClass can be defined in a registered autoloader, it is actually
// loaded and $a gets boolean value false ($o is not a OtherClass)
// if OtherClass can not be defined in a registered autoloader, a fatal
// error occurs.

$name = 'YetAnotherClass';
$a = $o instanceof $name; // YetAnotherClass is not defined!
// $a simply gets boolean value false, YetAnotherClass remains undefined.

從 PHP 5.1.0 版開始,在這些情況下不再呼叫已註冊的自動載入器。

較舊版本的 PHP(5.0 之前)

在早期版本的 PHP(5.0 之前)中,is_a 函式可用於確定物件是否屬於某個類。此函式在 PHP 版本 5 中已棄用,在 PHP 版本 5.3.0 中未過時。