我可以将实例化的对象用作数组键吗? [英] Can I use an instantiated Object as an Array Key?
本文介绍了我可以将实例化的对象用作数组键吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如:
$product = new Product("cat");
if(isset($sales[$product])){
$sales[$product]++;
}
else{
$sales[$product] = 1;
}
推荐答案
来自 文档:
数组和对象不能用作键.这样做会导致警告:Illegal offset type.
Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.
您可以给每个实例一个唯一的 ID 或覆盖 __toString()
这样它就会返回一些独特的东西,例如
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屋!
查看全文