php-doc-en/language/oop5/object-comparison.xml
2004-07-11 12:33:25 +00:00

118 lines
2.7 KiB
XML
Executable file

<?xml version="1.0" encoding="iso-8859-1"?>
<!-- $Revision: 1.1 $ -->
<sect1 id="language.oop5.object-comparison">
<title>Comparing objects</title>
<para>
In PHP 5, object comparison is a more complicated than in PHP 4 and more
in accordance to what one will expect from an Object Oriented Language
(not that PHP 5 is such a language).
</para>
<para>
When using the comparison operator (<literal>==</literal>),
object variables are compared in a simple manner, namely: Two object
instances are equal if they have the same attributes and values, and are
instances of the same class.
</para>
<para>
On the other hand, when using the identity operator (<literal>===</literal>),
object variables are identical if and only if they refer to the same
instance of the same class.
</para>
<para>
An example will clarify these rules.
<example>
<title>Example of object comparison in PHP 5</title>
<programlisting role='php'>
<![CDATA[
<?php
function bool2str($bool) {
if ($bool === false) {
return 'FALSE';
} else {
return 'TRUE';
}
}
function compareObjects(&$o1, &$o2) {
echo 'o1 == o2 : '.bool2str($o1 == $o2)."\n";
echo 'o1 != o2 : '.bool2str($o1 != $o2)."\n";
echo 'o1 === o2 : '.bool2str($o1 === $o2)."\n";
echo 'o1 !== o2 : '.bool2str($o1 !== $o2)."\n";
}
class Flag {
var $flag;
function Flag($flag=true) {
$this->flag = $flag;
}
}
class OtherFlag {
var $flag;
function OtherFlag($flag=true) {
$this->flag = $flag;
}
}
$o = new Flag();
$p = new Flag();
$q = $o;
$r = new OtherFlag();
echo "Two instances of the same class\n";
compareObjects($o, $p);
echo "\nTwo references to the same instance\n";
compareObjects($o, $q);
echo "\nInstances of two different classes\n";
compareObjects($o, $r);
?>
]]>
</programlisting>
</example>
This example will output:
<screen>
Two instances of the same class
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : FALSE
o1 !== o2 : TRUE
Two references to the same instance
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : TRUE
o1 !== o2 : FALSE
Instances of two different classes
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE
</screen>
</para>
</sect1>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"../../manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->