note 73804 added to language.oop5.object-comparison
| From: | dionyzizatdeviantartdotcom at osu1 dot php dot net | Date: | Sun, 11 Mar 2007 03:20:35 +0000 |
| Subject: | note 73804 added to language.oop5.object-comparison | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-124315@lists.php.net to get a copy of this message | ||
Note that classes deriving from the same parent aren't considered equal when comparing even
using ==; they should also be objects of the same child class.
<?php
class Mom {
private $mAttribute;
public function Mom( $attribute ) {
$this->mAttribute = $attribute;
}
public function Attribute() {
return $this->mAttribute;
}
}
final class Sister extends Mom {
public function Sister( $attribute ) {
$this->Mom( $attribute );
}
}
final class Brother extends Mom {
public function Brother( $attribute ) {
$this->Mom( $attribute );
}
}
$sister = new Sister( 5 );
$brother = new Brother( 5 );
assert( $sister == $brother ); // will FAIL!
?>
This assertion will fail, because sister and brother are not of the same child class!
If you want to compare based on the parent class object type only, you might have to define a
function for comparisons like these, and use it instead of the == operator:
<?php
function SiblingsEqual( $a, $b ) {
if ( !( $a instanceof Mom ) ) {
return false;
}
if ( !( $b instanceof Mom ) ) {
return false;
}
if ( $a->Attribute() != $b->Attribute() ) {
return false;
}
return true;
}
assert( SiblingsEqual( $sister, $brother ) ); // will succeed
?>
----
Server IP: 69.147.83.197
Probable Submitter: 89.19.68.198
----
Manual Page -- http://www.php.net/manual/en/language.oop5.object-comparison.php
Edit -- https://master.php.net/note/edit/73804
Del: integrated -- https://master.php.net/note/delete/73804/integrated
Del: useless -- https://master.php.net/note/delete/73804/useless
Del: bad code -- https://master.php.net/note/delete/73804/bad+code
Del: spam -- https://master.php.net/note/delete/73804/spam
Del: non-english -- https://master.php.net/note/delete/73804/non-english
Del: in docs -- https://master.php.net/note/delete/73804/in+docs
Del: other reasons-- https://master.php.net/note/delete/73804
Reject -- https://master.php.net/note/reject/73804
Search -- https://master.php.net/manage/user-notes.php