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 does PHP compare objects?

How to add comments in PHP

How to prevent Eloquent from adding created_at or updated_at timestamps?

How to get a route to directly show a view?

How to round a number in JS?

How to make Apache force download of files (in .htaccess)

How to pick what array_intersect function to use in PHP?

How to install and use optipng on Linux CentOS

How to Enable Directory Listings in Apache with .htaccess

How to select all rows for a certain month (or day, year or time), using Eloquent