php-doc-en/language/oop5/object-comparison.xml
Nilgün Belma Bugüner 04077dd209 fixed properties
git-svn-id: https://svn.php.net/repository/phpdoc/en/trunk@283798 c90b9560-bf6c-de11-be94-00142212c4b1
2009-07-11 06:17:58 +00:00

129 lines
2.9 KiB
XML

<?xml version="1.0" encoding="iso-8859-1"?>
<!-- $Revision$ -->
<sect1 xml:id="language.oop5.object-comparison" xmlns="http://docbook.org/ns/docbook">
<title>Comparing objects</title>
<para>
In PHP 5, object comparison is 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
{
public $flag;
function Flag($flag = true) {
$this->flag = $flag;
}
}
class OtherFlag
{
public $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.outputs;
<screen>
<![CDATA[
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>
</example>
</para>
<note>
<para>
Extensions can define own rules for their objects comparison.
</para>
</note>
</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
-->