note 75174 added to language.oop.object-comparison
| From: | Mildred | Date: | Wed, 16 May 2007 14:17:07 +0000 |
| Subject: | note 75174 added to language.oop.object-comparison | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-126642@lists.php.net to get a copy of this message | ||
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;
}
?>
----
Server IP: 195.221.21.36
Probable Submitter: 194.206.50.185
----
Manual Page -- http://www.php.net/manual/en/language.oop.object-comparison.php
Edit -- https://master.php.net/note/edit/75174
Del: integrated -- https://master.php.net/note/delete/75174/integrated
Del: useless -- https://master.php.net/note/delete/75174/useless
Del: bad code -- https://master.php.net/note/delete/75174/bad+code
Del: spam -- https://master.php.net/note/delete/75174/spam
Del: non-english -- https://master.php.net/note/delete/75174/non-english
Del: in docs -- https://master.php.net/note/delete/75174/in+docs
Del: other reasons-- https://master.php.net/note/delete/75174
Reject -- https://master.php.net/note/reject/75174
Search -- https://master.php.net/manage/user-notes.php