douwen3500 2014-03-07 20:53 采纳率: 0%
浏览 54
已采纳

PHP OOP按属性查找对象

I'm trying to pull a random instance of a class (object) by generating a random number and checking object ids against that number.

I've found a lot of info on how to retrieve an object attribute (specifically here it's the id) but not without knowing which object first.

So within my class I've got

public function getID() {
return $this->id;
}

But

getID()

only works if I use it as

$object->getID()

Is there a way to do something similar but for every object in a class, without specifying the objects?

I'm trying to avoid having to write if/then for every object in the class.

  • 写回答

2条回答 默认 最新

  • duanqu9279 2014-03-07 20:58
    关注

    You could set up an array of objects, then iterate over the array and call the getID() method on each object. If your array of objects is called $myObjects...

    foreach($myObjects as $object) {
        $object->getID();  //And do something with it
    }
    

    However, if you want to pick a random object out of a set of objects, testing a whole bunch of them to see if they are the object you picked isn't really ideal. You'd be better off putting them into an array and using array_rand() to select a random object out of the array.

    What's your purpose for doing this? That may indicate a better way to approach this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型