note 45570 added to language.operators.type

From: Date: Sat, 11 Sep 2004 05:00:16 +0000
Subject: note 45570 added to language.operators.type
Groups: php.notes 
Request: Send a blank email to php-notes+get-76438@lists.php.net to get a copy of this message
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>'; } ?> ---- Manual Page -- http://www.php.net/manual/en/language.operators.type.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+45570 Delete -- http://master.php.net/manage/user-notes.php?action=delete+45570&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+45570&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#76438) next »