PHP绫诲瀷杩愮畻绗


instanceof 鐢ㄤ簬纭畾涓涓 PHP 鍙橀噺鏄惁灞炰簬鏌愪竴绫 class 鐨勫疄渚嬶細
绫诲瀷杩愮畻绗
instanceof 鐢ㄤ簬纭畾涓涓 PHP 鍙橀噺鏄惁灞炰簬鏌愪竴绫 class 鐨勫疄渚嬶細

Example #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 涔熷彲鐢ㄦ潵纭畾涓涓彉閲忔槸涓嶆槸缁ф壙鑷煇涓鐖剁被鐨勫瓙绫荤殑瀹炰緥锛 can also be used to determine whether a variable is an instantiated object of a class that inherits from a parent class:

Example #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)
妫鏌ヤ竴涓璞 涓嶆槸 鏌愪釜绫荤殑瀹炰緥锛屽彲浠ヤ娇鐢 閫昏緫杩愮畻绗 not銆

Example #3 浣跨敤instanceof妫鏌ュ璞 涓嶆槸 鏌愪竴绫荤殑瀹炰緥

<?php
class MyClass
{
}

$a = new MyClass;
var_dump(!($a instanceof stdClass));
?>
浠ヤ笂渚嬬▼浼氳緭鍑猴細

bool(true)
鏈鍚庯紝instanceof涔熷彲鐢ㄤ簬纭畾涓涓彉閲忔槸涓嶆槸瀹炵幇浜嗘煇涓帴鍙g殑瀵硅薄鐨勫疄渚:

Example #4 Using instanceof for class

<?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 閫氬父鐩存帴涓庣被鍚嶄竴璧蜂娇鐢紝浣嗕篃鍙互浣跨敤瀵硅薄鎴栧瓧绗︿覆鍙橀噺锛

Example #5 Using instanceof with other variables

<?php
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'
?>
浠ヤ笂渚嬬▼浼氳緭鍑猴細

bool(true)
bool(true)
bool(false)
鐒惰 instanceof 鐨勪娇鐢ㄨ繕鏈変竴浜涢櫡闃卞繀椤讳簡瑙c傚湪 PHP 5.1.0涔嬪墠锛屽鏋滆妫鏌ョ殑绫诲悕绉颁笉瀛樺湪锛宨nstanceof 浼氳皟鐢 __autoload()銆傚彟澶栵紝濡傛灉璇ョ被娌℃湁琚杞藉垯浼氫骇鐢熶竴涓嚧鍛介敊璇傚彲浠ラ氳繃浣跨敤鍔ㄦ佺被寮曠敤(dynamic class reference)鎴栫敤涓涓寘鍚被鍚嶇殑瀛楃涓插彉閲忔潵閬垮紑杩欑闂锛

Example #6 閬垮厤 PHP 5.0 涓 instanceof 寮曡捣鐨勭被鍚嶆煡鎵惧拰鑷村懡閿欒闂

<?php
$d = 'NotMyClass';
var_dump($a instanceof $d); // no fatal error here
?>
浠ヤ笂渚嬬▼浼氳緭鍑猴細

bool(false)
instanceof 杩愮畻绗︽槸 PHP 5 寮曡繘鐨勩傚湪姝や箣鍓嶇敤 is_a()锛屼絾鏄 is_a() 宸茬粡杩囨椂浜嗭紝鏈濂界敤 instanceof銆

鍙傝 get_class() 鍜 is_a()銆

浠ヤ笂灏辨槸PHP绫诲瀷杩愮畻绗︾殑璇︾粏鍐呭锛屾洿澶氫俊鎭鍏虫敞OD浜戝叾瀹冪浉鍏虫枃绔狅紒



鏈枃URL锛http://www.odweb.cn/news_show.html?id=72