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;
  4. $b = new SomeClass();
  5. $b->something = 123;
  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
  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;
  4. $b = new SomeClass(); // different instance
  5. $b->something = 123;  // same values
  7. return $a === $b; // false

webdevetc profile pic

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


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 set up an alias to map one directory to another destination

How to reverse htmlentities() / What is the opposite of htmlentities()?

How to set the Expires header in .htaccess

How to set environmental variables in your .htaccess file

Is multiple inheritance supported in PHP?

How to check if a user is logged in, inside a blade file?

What kind of database field type should you (normally) use for foreign keys?

How to add the CSRF (Cross-site request forgery) token in Laravel?

How to undelete a soft deleted Eloquent row?

What are PHP's PSRs?