note 73804 deleted from language.oop5.object-comparison by sobak
| From: | sobak@php.net | Date: | Sat, 18 Apr 2020 18:58:46 +0000 |
| Subject: | note 73804 deleted from language.oop5.object-comparison by sobak | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-214498@lists.php.net to get a copy of this message | ||
Note Submitter: dionyziz at deviantart dot com
----
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
?>