note 75174 deleted from language.oop.object-comparison by danbrown

From: Date: Sat, 07 Nov 2009 19:01:42 +0000
Subject: note 75174 deleted from language.oop.object-comparison by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-162546@lists.php.net to get a copy of this message
Note Submitter: Mildred <silkensedai at online dot fr> ---- If you want to test the existance of objects in arrays like in_array but with very strict checking in PHP4 (in order to avoid the "Nesting level too deep - recursive dependency?" error). i wrote the following function. All objects that can be compared must extends comparable and call the comparable constructor. It will then create a serial number different on each objects. I don't think it is the ultimate solution because arrays can contains loops and this won't be checked here. And if there is a recursive dependency between objects that do not extends comparable, you will still have the error. Sometimes I think I don't like PHP very much ... <?php class comparable { // Don't forget to call this constructor in sub-classes function comparable(){ if(!isset($GLOBALS[__FILE__.'/class:comparable'])) $GLOBALS[__FILE__.'/class:comparable'] = 1; $this->comparableSerial = $GLOBALS[__FILE__.'/class:comparable']++; } } function exact_in_array(&$needle, &$haystack){ foreach($haystack as $k=>$v){ $elem = &$haystack[$k]; if( is_object($needle) and is_object($elem) and is_a($needle, 'comparable') and is_a($elem, 'comparable')) { if( get_class($needle) === get_class($elem) and $needle->comparableSerial == $elem->comparableSerial) return true; }else{ // Uncomment this line to know which classes do not extends // comparable and fail the test with Nesting level too deep error //printf( // "%s(%s) === %s(%s)", // $needle, get_class($needle), $elem, get_class($elem)); if($needle === $elem) return true; } unset($elem); } return false; } ?>

« previous php.notes (#162546) next »