Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

Can I check if an object is kind of a specific class, in PHP?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the instanceof operator, to check if an object is an instance of :

  • A class
  • Or a child class of that class
  • Or an instance of a class that implements an interface

Which means that it cannot be used to detect if your object is an instance of a specific class -- as it will say "yes" if your object is an instance of a child-class of that class.


For instance, this portion of code :

class ClassA {}
class ClassB extends ClassA {}

$a = new ClassB();
if ($a instanceof ClassA) {
    echo '$a is an instanceof ClassA<br />';
}
if ($a instanceof ClassB) {
    echo '$a is an instanceof ClassB<br />';
}

Will get you this output :

$a is an instanceof ClassA
$a is an instanceof ClassB

$a, in a way, is an instance of ClassA, as ClassB is a child-class of ClassA.

And, of course, $a is also an instance of ClassB -- see the line where it's instanciated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...