PHP: Оператор проверки принадлежности к классу - Manual

downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Control Structures Операторы, работающие с массивами

Last updated: Fri, 26 Jan 2007

view this page in

# Оператор проверки принадлежности к классу

Оператор `instanceof` используется для определения того, является ли текущий объект экземпляром указанного класса .

Оператор `instanceof` был добавлен в PHP 5. До этого использовалась конструкция is_a(), которая на данный момент не рекомендуется к применению, более предпочтительно использовать оператор `instanceof` .

    <?php
    class A { }
    class B { }

    $thing = new A;

    if ($thing instanceof A) {
        echo 'A';
    }
    if ($thing instanceof B) {
        echo 'B';
    }
    ?>

Поскольку объект `$thing` является экземпляром класса A, и никак не B, то будет выполнен только первый, опирающийся на класс A, блок:

    A

Ознакомьтесь также с описанием функций get_class() и is_a().

add a note User Contributed Notes
Оператор проверки принадлежности к классу
soletan at toxa dot de
03-Mar-2007 04:04
`Please note: != is a separate operator with separate semantics. Thinking about language grammar it's kind of ridicilous to negate an operator. Of course, it's possible to negate the result of a function (like is_a()), since it isn't negating the function itself or its semantics.
instanceof is a binary operator, and so used in binary terms like this
terma instanceof termb
while ! (negation) is a unary operator and so may be applied to a single term like this
!term
And a term never consists of an operator, only! There is no such construct in any language (please correct me!). However, instanceof doesn't finally support nested terms in every operand position ("terma" or "termb" above) as negation does:
!!!!!!!!!!!!!!term == term
So back again, did you ever write
a !!!!!!!!!!!!= b
to test equivalence?`
mikael dot knutsson at gmail dot com
05-Dec-2006 08:34
`I can confirm what thisbizness at gmail dot com said just below in PHP 5.2, furthermore, people looking to use this as a "if $a is not instance of A" for error throwing purposes or other, just type it like this:
<?php
if( !$a instanceof A ) {
throw new Exception( '$a is not instance of A.' );
}
?>
This also works if $a is not an object, or not even set (you will get an E_NOTICE if it isn't set though).
A note worth making is that if you are unsure of if class A is present when making this comparison, and you don't want to trigger the __autoload() magic method, scroll down for examples of how to get around this.
I was unsure about it at first since most other operators have their own negative (like !=) or they are/can be used as function calls (like !is_a()) but it is this simple. Hope it helps someone.
Until again!`
archanglmr at yahoo dot com
17-Feb-2005 06:37
`Negated instanceof doesn't seem to be documented. When I read instanceof I think of it as a compairson operator (which I suppose it's not).
<?php
class A {}
class X {}
//parse error from !
if (new X !instanceof A) {
throw new Exception('X is not an A');
}
//proper way to negate instanceof ?
if (!(new X instanceof A)) {
throw new Exception('X is not an A');
}
?>`
d dot schneider at 24you dot de
18-Dec-2004 12:42
`use this for cross-version development...
<?php
function is_instance_of($IIO_INSTANCE, $IIO_CLASS){
if(floor(phpversion()) > 4){
if($IIO_INSTANCE instanceof $IIO_CLASS){
return true;
}
else{
return false;
}
}
elseif(floor(phpversion()) > 3){
return is_a($IIO_INSTANCE, $IIO_CLASS);
}
else{
return false;
}
}
?>`
add a note
Control Structures Операторы, работающие с массивами

Last updated: Fri, 26 Jan 2007
show source | credits | stats | sitemap | contact | advertising | mirror sites
Copyright © 2001-2007 The PHP Group
All rights reserved.
This mirror generously provided by: Yahoo! Inc.
Last updated: Sat Mar 10 09:32:46 2007 PST