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 group a SQL statement in brackets/parenthesis

How to prevent Eloquent from adding created_at or updated_at timestamps?

How to hide directory listing in .htaccess?

How to block IP addresses in Apache by using regular expressions (regex) in .htaccess

How to convert between types in JS?

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

How to order a Laravel hasMany relationship?

Point all requests to one PHP file

How to set up an alias to map one directory to another destination

How to find out which php.ini file PHP is using?