|
| 1 | +[<-- Return to index](../README.md) |
| 2 | +# Comparisons of References and Values |
| 3 | + |
| 4 | +### How are values compared? |
| 5 | +#### PHP |
| 6 | +When objects are compared with the comparison operator `==`, the objects will be considered equal if their attributes and values match and are both instances of the same class. |
| 7 | + |
| 8 | +When objects are compared with the identity operator `===`, the objects will be considered equal if they both refer to the same reference of an object. |
| 9 | +```php |
| 10 | +<?php |
| 11 | + class myClass { |
| 12 | + public $foo; |
| 13 | + public $bar; |
| 14 | + function __construct($foo, $bar) { |
| 15 | + $this->foo = $foo; |
| 16 | + $this->bar = $bar; |
| 17 | + } |
| 18 | + } |
| 19 | + |
| 20 | + $a = new myClass("apples", "oranges"); |
| 21 | + $b = new myClass("apples", "oranges"); |
| 22 | + $c = $a; |
| 23 | + |
| 24 | + ($a == $b) ? print "a equals b" : print "a does not equal b"; |
| 25 | + ($a === $b) ? print "a and b reference the same object" : print "a and b do not reference the same object"; |
| 26 | + ($a === $c) ? print "a and c reference the same object" : print "a and c do not reference the same object"; |
| 27 | +?> |
| 28 | +``` |
| 29 | +Will yield: |
| 30 | +``` |
| 31 | +a equals b |
| 32 | +a and b do not reference the same object |
| 33 | +a and c reference the same object |
| 34 | +``` |
| 35 | +#### Python |
| 36 | +Equality in Python is compared with the `==` operator. To check if two objects share the same reference, Python uses the `is` keyword. However when comparing objects, Python does not necessarily natively verify that the objects are identical purely by value like PHP. This can be resolved by manually overriding the `__eq__()` method. |
| 37 | +```python |
| 38 | +class myClass: |
| 39 | + def __init__(self, foo, bar): |
| 40 | + self.foo = foo |
| 41 | + self.bar = bar |
| 42 | + def __eq__(self, other): |
| 43 | + return self.__dict__ == other.__dict__ |
| 44 | + |
| 45 | +a = myClass("apples", "oranges") |
| 46 | +b = myClass("apples", "oranges") |
| 47 | +c = a |
| 48 | + |
| 49 | +print("a equals b") if (a == b) else print("a does not equal b") |
| 50 | +print("a and c reference the same object") if (c is a) else print("a and c do not reference the same object") |
| 51 | +``` |
| 52 | +Will yield: |
| 53 | +``` |
| 54 | +a equals b |
| 55 | +a and c reference the same object |
| 56 | +``` |
0 commit comments