PHP: Comparing Objects using == and ===


/ Published in: PHP
Save to your folder(s)

Here are a few examples that show how the relationship between objects and references


Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. class Box{
  4. public $name = "box";
  5. }
  6.  
  7. $box = new Box();
  8. $box_reference = $box;
  9. $box_clone = clone $box;
  10.  
  11. $box_changed = clone $box;
  12. $box_changed->name = "changed box";
  13.  
  14. $another_box = new Box();
  15.  
  16. // Attributes are pretty much the same
  17. echo $box == $box_reference ? 'true' : 'false';
  18. echo "<br />";
  19. echo $box == $box_clone ? 'true' : 'false';
  20. echo "<br />";
  21. echo $box == $box_changed ? 'true' : 'false';
  22. echo "<br />";
  23. echo $box == $another_box ? 'true' : 'false';
  24. echo "<br />";
  25. echo "<br />";
  26. // Checks to see if they reference the same object
  27. echo $box === $box_reference ? 'true' : 'false';
  28. echo "<br />";
  29. echo $box === $box_clone ? 'true' : 'false';
  30. echo "<br />";
  31. echo $box === $box_changed ? 'true' : 'false';
  32. echo "<br />";
  33. echo $box === $another_box ? 'true' : 'false';
  34. echo "<br />";
  35.  
  36. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.