Bug #72220 [Opn->Nab]: Loose anonymous class comparison inconsistency
Edit report at https://bugs.php.net/bug.php?id=72220&edit=1
ID: 72220
Updated by: requinix@php.net
Reported by: remyfox at hotmail dot com
Summary: Loose anonymous class comparison inconsistency
-Status: Open
+Status: Not a bug
Type: Bug
Package: Class/Object related
Operating System: Windows
PHP Version: 7.0.6
Block user comment: N
Private report: N
New Comment:
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
Previous Comments:
------------------------------------------------------------------------
[2016-05-15 19:18:17] 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());
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=72220&edit=1
Thread (2 messages)