I noticed that anonymous classes created using the same method are the same classes.
function test($test) {
return new class($test) {
public function __construct(public $test) {}
};
}
function test2($test) {
return new class($test) {
public function __construct(public $test) {}
};
}
function compare($a, $b) {
var_dump([
$a == $b,
$a === $b,
get_class($a) == get_class($b),
]);
}
compare(test(1), test(1)); // true, false, true,
compare(test(['abc']), test(1)); // false, false, true,
compare(test(1), test2('xx')); // false, false, false
compare(test('xx'), test2('xx')); // false, false, false
I explain it to myself in such a way that PHP simply substitutes a random name there. So in reality there is simply a class with some name, and running the same function multiple times does not change the name, so the class is the same.
However, I wonder how to generate a class using one code, which have the same syntax but are different classes. Because now I cannot imagine copying this and creating test3()
, test4()
, test5()
, ...
, test50()
, and so on, depending on how many different classes I would need.
More context
I was creating test for a certain method.
To call the method, a class implementing some interface was needed.
I decided that I would not test existing classes, but would create an anonymous class in which I would implement that interface.
The interface contains only 1 method that must return a string.
So I generate random string before creating the class object, then set a field through the constructor, and the method would return the value of this field.
But I decided that one test was not enough.
So I wanted to create more such cases and ran 50x method.
Unfortunately, inside this mechanism, a check is performed based on the ::class
. So having 50 different objects that returned different values from the method doesnt matter, as long as they were the same classes, and from the point of view of this mechanism it was important (I will not go into details why, because it took some time), hence my question.