Can I use an instantiated Object as an Array Key?

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

    You can use http://www.php.net/manual/en/class.splobjectstorage.php

    $product = new Product("cat");
    $sales = new SplObjectStorage();
    if(isset($sales[$product])){
         $sales[$product]++;
    }
    else{
         $sales[$product] = 1;
    }
    

    It's not a real array, but has a decent amount of array-like functionality and syntax. However, due to it being an object, it behaves like a misfit in php due to its odd foreach behavior, and its incompatibility with all the native php array functions. Sometimes you'll find it useful to convert it to a real array via

    $arr = iterator_to_array($sales);
    

    so it plays nice with the rest of your codebase.

提交回复
热议问题