0

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.

Andy_D
  • 4,112
  • 27
  • 19
  • 1
    "object in a class" you mean you're embedding other objects inside a class, e.g. `$foo->bar->baz()` where bar is some OTHER object that's different from the class that foo is an instance of? – Marc B Mar 07 '14 at 20:58
  • The technical terms are a bit confused here. There is no such thing as "objects in a class". A class is a blue print from which objects are created. Second, objects do not contain objects. An object can contain an array which can contain objects (an object can contain one object, as an attribute). If you are targeting a method (function) of a class then you have to provide an object. This object can be of anonymous naming, meaning `$object->getID()` or `$item->getID()` can contain the very same object. – dbf Mar 07 '14 at 21:13
  • Marc B and dbf thanks for the comments, looks like I complicated the issue with my wording. These objects are just instances of one class. – Andy_D Mar 07 '14 at 21:25

2 Answers2

0

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.

Surreal Dreams
  • 26,055
  • 3
  • 46
  • 61
  • I think array_rand() will work and is a simpler solution than the way I'm going about it. Thanks for the tip. – Andy_D Mar 07 '14 at 21:28
0

I think you'd have to have planned for this eventuality, then loop thru the candidate objects as @Surreal Dreams; suggests.

See Get all instances of a class in PHP

Community
  • 1
  • 1
Cups
  • 6,901
  • 3
  • 26
  • 30