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条)

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了