Can I use an instantiated Object as an Array Key?

前端 未结 6 1328
执笔经年
执笔经年 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:21

    If the object is a simple predefined classes made with new stdClass() it may be valid option to use the json representation of this class with json_encode.

    $product = new stdClass();
    $product->brand = "Acme";
    $product->name = "Patator 3.14";
    
    $product_key = json_encode($product);
    
    if(isset($sales[$product_key])){
         $sales[$product_key]++;
    }
    else{
        $sales[$product_key] = 1;
    }
    

    But keep in mind that the equality of two objects is always a business model choice and must be carefully designed.

提交回复
热议问题