|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[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());
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Mon Nov 17 17:00:01 2025 UTC |
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