note 45570 deleted from language.operators.type by colder

From: Date: Sat, 24 Feb 2007 10:01:23 +0000
Subject: note 45570 deleted from language.operators.type by colder
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-123808@lists.php.net to get a copy of this message
Note Submitter: glen at arkadia-systems dot com ---- If you are updating code to replace 'is_a()' with the PHP5 compliant 'instanceof' operator, you may find it necessary to change the basic architecture of your code to make this work. 'instanceof' will throw a fatal error if the object being checked for does not exist. 'is_a()' will simply return false under this condition. In the example below, 'is_a()' would effectively detect the need to create an instance of class 'A', but in this case 'instanceof' will crash your program with a fatal error. <?php // define classes // Commenting this class will cause an error when 'instanceof' looks for 'A' // class A {} class B {} // create a new object // $thing = new A(); $thing = new B(); if (is_a($thing, 'A')) { echo 'Yes, $thing is_a A<br>'; } else { echo 'No, $thing is not is_a A<br>'; } if ($thing instanceof A) { echo 'Yes, $thing is an instaceof A<br>'; } else { echo 'No, $thing is not an instaceof A<br>'; } ?> >>> Output: No, $thing is not is_a A Fatal error: Class 'A' not found in is_a-instanceof.php on line 19 >>> A suitable work-around for this situation is to check for the existence of the class before performing the 'instanceof' comparison: <?php /* ... */ if (class_exists('A') && $thing instanceof A) { echo 'Yes, $thing is an instaceof A<br>'; } else { echo 'No, $thing is not an instaceof A<br>'; } ?>

« previous php.notes (#123808) next »