Home  >  Article  >  Backend Development  >  Usage of instanceof keyword in php object-oriented

Usage of instanceof keyword in php object-oriented

巴扎黑
巴扎黑Original
2017-04-17 16:48:222688browse

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!

Statement:
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