Can I use an instantiated Object as an Array Key?

前端 未结 6 1344
执笔经年
执笔经年 2020-12-15 15:47

For example:

$product = new Product(\"cat\");

if(isset($sales[$product])){
     $sales[$product]++;
}
else{
     $sales[$product] = 1;
}
6条回答
  •  孤街浪徒
    2020-12-15 16:22

    From the docs:

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

    You could give each instance a unique ID or override __toString() such that it returns something unique and do e.g.

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

提交回复
热议问题