gpt4 book ai didi

PHP 7 - 比较匿名类实例

转载 作者:可可西里 更新时间:2023-11-01 12:18:19 25 4
gpt4 key购买 nike

我试过这段代码:

$ac1 = new class {};
$ac2 = new class {};

var_dump($ac1); // object(class@anonymous)#1 (0) {}
var_dump($ac2); // object(class@anonymous)#2 (0) {}
var_dump(new class {}); // object(class@anonymous)#3 (0) {}

var_dump($ac1 == $ac2); // bool(false)
var_dump($ac1 == new class {}); // bool(false)
var_dump($ac2 == new class {}); // bool(false)

以上比较的结果都是false

但是,当我声明一个返回匿名类的函数时,结果是这样的:

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

$ac1 = anonymous_class();
$ac2 = anonymous_class();

var_dump($ac1); // object(class@anonymous)#1 (0) {}
var_dump($ac2); // object(class@anonymous)#2 (0) {}
var_dump(anonymous_class()); // object(class@anonymous)#3 (0) {}

var_dump($ac1 == $ac2); // bool(true)
var_dump($ac1 == anonymous_class()); // bool(true)
var_dump($ac2 == anonymous_class()); // bool(true)

所有打印的 true

现在,问题是,这是怎么发生的?特别是,为什么它在知道每个 var_dump() 实例的结果不同的情况下为第二个上下文打印 true

最佳答案

来自文档 http://php.net/manual/en/language.oop5.anonymous.php

All objects created by the same anonymous class declaration are instances of that very class.

<?php
function anonymous_class()
{
return new class {};
}

if (get_class(anonymous_class()) === get_class(anonymous_class())) {
echo 'same class';
} else {
echo 'different class';
}

The above example will output: same class

来自http://php.net/manual/en/language.oop5.object-comparison.php

When using the comparison operator ==, object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values (values are compared with ==), and are instances of the same class.

关于PHP 7 - 比较匿名类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39891795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com