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类'; }
(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 '你也一起来吧'; }
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!