gpt4 book ai didi

php - 我可以使用实例化的对象作为数组键吗?

转载 作者:IT王子 更新时间:2023-10-29 01:11:12 24 4
gpt4 key购买 nike

例如:

$product = new Product("cat");

if(isset($sales[$product])){
$sales[$product]++;
}
else{
$sales[$product] = 1;
}

最佳答案

来自docs :

Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.

你可以给每个实例一个唯一的 ID 或者覆盖 __toString()这样它会返回一些独特的东西并做例如

$array[(string) $instance] = 42;

关于php - 我可以使用实例化的对象作为数组键吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4642980/

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