Home >Backend Development >PHP Tutorial >php object comparison

php object comparison

伊谢尔伦
伊谢尔伦Original
2016-11-23 13:54:241038browse

Object comparison in PHP 5 is more complex than in PHP 4, and the desired result is more consistent with an object-oriented language.

When using the comparison operator (==) to compare two object variables, the principle of comparison is: if the attributes and attribute values ​​​​of the two objects are equal, and the two objects are instances of the same class, then the two objects Object variables are equal.

If you use the equality operator (===), these two object variables must point to the same instance of a certain class (that is, the same object).

The above principles can be understood through the following examples.

Example #1 Object comparison of PHP 5

<?php
function bool2str($bool)
{
    if ($bool === false) {
        return &#39;FALSE&#39;;
    } else {
        return &#39;TRUE&#39;;
    }
}
function compareObjects(&$o1, &$o2)
{
    echo &#39;o1 == o2 : &#39; . bool2str($o1 == $o2) . "\n";
    echo &#39;o1 != o2 : &#39; . bool2str($o1 != $o2) . "\n";
    echo &#39;o1 === o2 : &#39; . bool2str($o1 === $o2) . "\n";
    echo &#39;o1 !== o2 : &#39; . 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);
?>

The above routine will output:

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

Note:

You can define the principles of object comparison by yourself in the PHP extension.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:php type constraintsNext article:php type constraints