How does PHP compare objects?

PHP: How does PHP compare objects?

If two objects are compared with ==, then it will check if:

1) - they are two instances of the same type of class

2) - they have the same properties

3) - and those properties have the same values

  1. $a = new SomeClass();
  2. $a->something = 123;
  3.  
  4. $b = new SomeClass();
  5. $b->something = 123;
  6.  
  7. return $a == $b; // true

If two objects are compared with ===, then PHP will return true only if both variables are pointing to the exact same object (the same instance of the object). Remember that objects are always passed by value.

For example, the following will return true:

  1. $a = new SomeClass();
  2. $a->something = 123;
  3. $b = $a; // $a and $b point to the exact same instance
  4.  
  5. return $a === $b; // true

However, the following (using ===) will return false. If the check was with == then it would return true, as the class type/properties/values are the same

  1. $a = new SomeClass();
  2. $a->something = 123;
  3.  
  4. $b = new SomeClass(); // different instance
  5. $b->something = 123;  // same values
  6.  
  7. return $a === $b; // false

webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about How does PHP compare objects?

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the PHP language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

What are PHP's PSRs?

How to find an item by Primary Key in Eloquent, or throw a ModelNotFoundException exception if it isn't found?

What does PEAR stand for?

What is the difference between empty(), isset(), != null, is_null() in PHP

How to undelete a soft deleted Eloquent row?

How to check if two strings are anagrams in PHP?

How to block IPv6 IP addresses in .htaccess

What are the main error types in PHP

How to add and remove items to an array in JS?

How to create random numbers in JS?