php check class instance of

Оператор проверки типа

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

Пример #1 Использование instanceof с классами

class NotMyClass
<
>
$a = new MyClass ;

Результат выполнения данного примера:

Оператор instanceof также может быть использован для определения, наследует ли определенный объект какому-либо классу:

Пример #2 Использование instanceof с наследуемыми классами

class MyClass extends ParentClass
<
>

Результат выполнения данного примера:

Для проверки непринадлежности объекта некоторому классу, используйте логический оператор not.

Пример #3 Использование instanceof для проверки того, что объект не является экземпляром класса

Результат выполнения данного примера:

Ну и наконец, instanceof может быть также использован для проверки реализации объектом некоторого интерфейса:

Пример #4 Использование instanceof для класса

class MyClass implements MyInterface
<
>

Результат выполнения данного примера:

Хотя instanceof обычно используется с прямо указанным именем класса, он также может быть использован с другим объектом или строковой переменной:

Пример #5 Использование instanceof с другими переменными

class MyClass implements MyInterface
<
>

$a = new MyClass ;
$b = new MyClass ;
$c = ‘MyClass’ ;
$d = ‘NotMyClass’ ;

Результат выполнения данного примера:

Пример #6 Пример использования оператора instanceof для проверки других переменных

Результат выполнения данного примера:

Есть несколько подводных камней, которых следует остерегаться. До версии PHP 5.1.0, instanceof вызывал __autoload() если имя класса не существовало. Вдобавок, если класс не был загружен, происходила фатальная ошибка. Это можно было обойти с помощью динамической ссылки на класс или использования строковой переменной с именем класса:

Пример #7 Избежание поиска класса и фатальных ошибок с instanceof в PHP 5.0

Результат выполнения данного примера:

Источник

Checking if an instance’s class implements an interface?

Given a class instance, is it possible to determine if it implements a particular interface? As far as I know, there isn’t a built-in function to do this directly. What options do I have (if any)?

6 Answers 6

You can use the «instanceof» operator. To use it, the left operand is a class instance and the right operand is an interface. It returns true if the object implements a particular interface.

class_implements() is part of the SPL extension.

Performance Tests

Some simple performance tests show the costs of each approach:

Given an instance of an object

Given only a class name

Where the expensive __construct() is:

These tests are based on this simple code.

nlaq points out that instanceof can be used to test if the object is an instance of a class that implements an interface.

You can also use the reflection API in PHP to test this more specifically:

php check class instance of. Смотреть фото php check class instance of. Смотреть картинку php check class instance of. Картинка про php check class instance of. Фото php check class instance of

Just to help future searches is_subclass_of is also a good variant (for PHP 5.3.7+):

php check class instance of. Смотреть фото php check class instance of. Смотреть картинку php check class instance of. Картинка про php check class instance of. Фото php check class instance of

Update

The is_a function is missing here as alternative.

I did some performance tests to check which of the stated ways is the most performant.

Results over 100k iterations

Added some dots to actually «feel» see the difference.

Conclusion

In case you have an object to check, use instance of like mentioned in the accepted answer.

Bonus

Источник

Php check class instance of

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

Пример #1 Использование instanceof с классами

class NotMyClass
<
>
$a = new MyClass ;

Результат выполнения данного примера:

Оператор instanceof также может быть использован для определения, наследует ли определённый объект какой-либо класс:

Пример #2 Использование instanceof с наследуемыми классами

class MyClass extends ParentClass
<
>

Результат выполнения данного примера:

Пример #3 Использование instanceof для проверки того, что объект не является экземпляром класса

Результат выполнения данного примера:

Наконец, instanceof может быть также использован для проверки реализации объектом некоторого интерфейса:

Пример #4 Использование instanceof с интерфейсами

class MyClass implements MyInterface
<
>

Результат выполнения данного примера:

Хотя instanceof обычно используется с прямо указанным именем класса, он также может быть использован с другим объектом или строковой переменной:

Пример #5 Использование instanceof с другими переменными

class MyClass implements MyInterface
<
>

$a = new MyClass ;
$b = new MyClass ;
$c = ‘MyClass’ ;
$d = ‘NotMyClass’ ;

Результат выполнения данного примера:

Пример #6 Пример использования оператора instanceof для проверки других переменных

Результат выполнения данного примера:

Пример #7 Использование instanceof для проверки констант

Результат выполнения данного примера в PHP 7.3:

Смотрите также

User Contributed Notes 23 notes

Checking an object is not an instance of a class, example #3 uses extraneous parentheses.

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:

$a = new A ;
$b = new B ;
$a2 = new A ;

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:

You can use «self» to reference to the current class:

If you want to test if a classname is an instance of a class, the instanceof operator won’t work.

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.

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.

Finally, here is a fast (to me) sample function code to verify if an object or class:

The first parameter must be an object instance.

example:
class A <>
class B extends A <>

var_dump ( A ::class instanceof B ); // false
var_dump ( B ::class instanceof A ); // false
var_dump (new B () instanceof A ); // true

You will have to do:

Example #5 could also be extended to include.

var_dump($a instanceof MyInterface);

The new result would be

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

SIMPLE, CLEAN, CLEAR use of the instanceof OPERATOR

?>

Now instantiate a few instances of these types. Note, I will put them in an array (collection) so we can iterate through them quickly.

?>

$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]

?>

Consider it an alternative to «get_class($bar) == get_class($foo)» that avoids the detour through to string lookups and comparisons.

if you have only class names (not objects) you can use that snippet: https://3v4l.org/mUKUC
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

Using an undefined variable will result in an error.

If variable is in doubt, one must prequalify:

Cross version function even if you are working in php4
(instanceof is an undefined operator for php4)

instanceof is a binary operator, and so used in binary terms like this

terma instanceof termb

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:

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *