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

How to show (or log) all SQL queries executed by Laravel

What are the SPL data structures

How to set up custom error pages in .htaccess for your Apache server (ErrorDocument)

How to hide directory listing in .htaccess?

How to change the order that migrations happen?

What is YAGNI?

How to get the type of a variable in JS?

How to install and use jpegoptim on Linux CentOS

How to Extract Query String (from a URL) Into an Associative Array in PHP

What is Agile software development?