Usage of instanceof keyword in php object-oriented

巴扎黑
Release: 2023-03-07 14:22:01
Original
2867 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.

<?php
header("content-type:text/html;charset=utf-8");
class Itbook{
}
class phpBook extends Itbook{
private $bookname;
}
$phpbook = new phpBook();
if($phpbook instanceof phpBook){
echo &#39;$phpbook属于phpBook类<br/>&#39;;
}
if($phpbook instanceof Itbook){
echo &#39;$phpbook属于Itbook类&#39;;
}
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 &#39;php中文网&#39;;
}
}
$exampleInstance = new ExampleClass();
if($exampleInstance instanceof ExampleInterface){
echo &#39;我在php中文网&#39;;
}else{
echo &#39;你也一起来吧&#39;;
}
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template