Usage of instanceof keyword in php object-oriented

巴扎黑
Release: 2023-03-07 14:22:01
Original
2773 people have browsed it

instanceof is a new keyword in php5. It has two functions:(1) Determine whether an object is an instance of a certain class, (2) Determine whether an object implements a certain interface.

The general format is: ObjectName instanceof ClassName

(1) Determine whether an object is an instance of a certain class

The following is the Let’s look at an example of one usage:

First create a parent class, and then create a subclass to inherit the parent class. Instantiate the subclass object, then determine whether the object belongs to the subclass, and then determine whether it belongs to the parent class.

'; } if($phpbook instanceof Itbook){ echo '$phpbook属于Itbook类'; }
Copy after login

(2) Determine whether an object implements a certain interface

The above is the first usage example of instanceof, let’s write about the second one below Usage example:

interface ExampleInterface { public function interfaceMethod(); } class ExampleClass implements ExampleInterface { public function interfaceMethod() { return 'php中文网'; } } $exampleInstance = new ExampleClass(); if($exampleInstance instanceof ExampleInterface){ echo '我在php中文网'; }else{ echo '你也一起来吧'; }
Copy after login

Code interpretation:

First create an interface class ExampleInterface, define methods, then create a subclass interface and define methods. Then instantiate the interface, and then judge. It is actually similar to the first usage, except that the keywords are changed, and everything else is the same.

The above is the detailed content of Usage of instanceof keyword in php object-oriented. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!