开发者

Mixing arrays and objects

I feel bad about mixing arrays with objects, but I'm not sure that I should.

// Populate array
foreach($participants as $participant){
   $participants[$key]['contestant'] = new Contestant($participant);
   $participants[$key]['brand'] = new Brand($brand);
   $key++;
}

[...]

// Print array
foreach($participants as $participant){
   print "Name: " . $participant['contestant']->name;
   print "Nationality: " . $participant['contestant']->nationality;
}
开发者_如何学运维

I'm not comfortable about the $contestant['contestant']->name part. I'd feel better about using objects exclusively.

Is it in fact considered bad practice to mix objects and arrays, or am I obsessing over something that everyone else thinks is fine?


It feels fine to me. Where an array makes sense, use an array. Where an object makes sense, use an object.

However, maybe you feel that a participant makes more sense as an object, which, looking at this relatively small code sample, it just may. If so, write up a quick Participant class. If that feels like too much overhead, then don't worry about it. At this point, it's personal preference, since your code, does, in fact, work. It's all about which codebase you would prefer to be working with in the future.


You're worrying yourself unnecessarily. It's fairly commonplace in other languages to mix sequences/mappings with objects. Arrays are useful when you don't know the number of elements or only a "ragtag" set of elements exist, and objects are useful when you know exactly the number of elements, and said elements each have a specific purpose.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜