我可以用一个实例化对象作为数组键? [英] Can I use an instantiated Object as an Array Key?
本文介绍了我可以用一个实例化对象作为数组键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如:
$ =产品的新产品(猫);如果(使用isset($销售额[$产品)){
销售额$ [$产品] ++;
}
其他{
销售额$ [$产品] = 1;
}
解决方案
从文档
数组和对象不能被用作密钥。这样做会导致一个警告:非法偏移类型
块引用>您可以给每个实例一个唯一的ID或重写<一个href=\"http://www.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring\"><$c$c>__toString()$c$c>这样,它返回独特的东西,例如做
$阵列[(字符串)$实例] = 42;
For example:
$product = new Product("cat"); if(isset($sales[$product])){ $sales[$product]++; } else{ $sales[$product] = 1; }
解决方案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;
这篇关于我可以用一个实例化对象作为数组键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文