简体   繁体   English

PHP OOP按属性查找对象

[英]PHP OOP find object by attribute

I'm trying to pull a random instance of a class (object) by generating a random number and checking object ids against that number. 我试图通过生成随机数并根据该数字检查对象ID来拉取类(对象)的随机实例。

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. 我已经找到了很多有关如何检索对象属性的信息(特别是这里的ID),但并非不先知道哪个对象。

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. 我试图避免必须为类中的每个对象编写if / then。

You could set up an array of objects, then iterate over the array and call the getID() method on each object. 您可以设置一个对象数组,然后遍历该数组并在每个对象上调用getID()方法。 If your array of objects is called $myObjects... 如果您的对象数组称为$ 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. 您最好将它们放入数组中,并使用array_rand()从数组中选择一个随机对象。

What's your purpose for doing this? 您这样做的目的是什么? That may indicate a better way to approach this. 这可能表明解决此问题的更好方法。

I think you'd have to have planned for this eventuality, then loop thru the candidate objects as @Surreal Dreams; 我认为您必须为此作好准备,然后循环通过@Surreal Dreams作为候选对象; suggests. 建议。

See Get all instances of a class in PHP 请参阅获取PHP中类的所有实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM