php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #72220 Loose anonymous class comparison inconsistency
Submitted: 2016-05-15 19:18 UTC Modified: 2016-05-15 20:03 UTC
From: remyfox at hotmail dot com Assigned:
Status: Not a bug Package: Class/Object related
PHP Version: 7.0.6 OS: Windows
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: remyfox at hotmail dot com
New email:
PHP Version: OS:

 

 [2016-05-15 19:18 UTC] remyfox at hotmail dot com
Description:
------------
When two new anonymous class instances are returned from a function, then they are equal. When they are instantiated and directly compared, then they are unequal. Comparison happens with the == operator.

Test script:
---------------
// Returns false.
var_dump(new class{} == new class {});

$a = function() {
	return new class{};
};

function b() {
	return new class{};
}

// Returns true.
var_dump($a() == $a());

// Returns true.
var_dump(b() == b());


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-05-15 20:03 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2016-05-15 20:03 UTC] requinix@php.net
It's not to do with being returned from a function or not. It has to do with the definition of the class, and loose equality requires the two be instances of the same definition (as well as having matching properties and values) [1].

Every place in the code where anonymous class definition appears gets internally a distinct class definition and name. Every time the code executes a new instance will be created of the class; the instances will be different but they will be of the same class.

With
  var_dump(new class{} == new class {});
there are two class definitions here: one on the LHS and the other on the RHS. Even though they both have the same set of properties (ie, none) they are different classes and thus their instances are not equal.

With each of
  var_dump($a() == $a());
  var_dump(b() == b());
the two values being compared are of the same definition: the one defined in $a and in b(), respectively.

The difference is more apparent using get_class(): https://3v4l.org/Dg6i0

[1] http://php.net/manual/en/language.oop5.object-comparison.php
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Apr 26 04:01:30 2024 UTC