Re: instanceof / __CLASS__ question
| From: | Greg Beaver | Date: | Tue, 31 Aug 2004 20:27:47 +0000 |
| Subject: | Re: instanceof / __CLASS__ question | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-195336@lists.php.net to get a copy of this message | ||
Hi,
I'm not sure I understand why you would use instanceof on $this. Try this code:
<?php
class a1 {
}
class a2 extends a1 {
}
echo new a1 instanceof a1; // true
echo new a2 instanceof a1; // true
?>
instanceof defines whether an object is or descends from a class (like is_a()).
If you want to check whether $this is the Test class or a descendant class, the simplest way I know is
if (get_class($this) == 'Test')
otherwise, you could use reflection
$z = new ReflectionClass($this);
if ($z->getName() == 'Test')
but that's a bit more cumbersome.
Greg
Jason Barnett wrote:
It's only a minor nuisance, but in order to use __CLASS__ with instanceof I have to assign __CLASS__ to a variable first. Should I bother submitting a bug report for this? Or am I perhaps missing something... <?php class Test { function checkObj2() {//workaround $class = __CLASS__; if ($this instanceof $class) { return TRUE; } else { return FALSE; }} function checkObj() {// this causes a parsing error // return ($this instanceof __CLASS__);} } $t = new Test(); echo $t->checkObj2() ? 'TRUE' : 'FALSE'; echo $t->checkObj(); // can't even test it ?>