0

I have a code in which an array contains objects, which have objects in them, for example:

<?php
class person {
    public $name;
    public $foods=array();
}
class food {
    public $foodnames=array() ;
}
$peoplearray[$name] = new person;
$peoplearray[$name]->name = 'john' ;
$peoplearray[$name]->foods[$key] = new food;
$peoplearray[$name]->foods[$key]->foodnames[$key] = 'ice cream' ;
$peoplearray[$name]->foods[$key] = new food;
$peoplearray[$name]->foods[$key]->foodnames[$key] = 'banana' ;

$peoplearray[$name] = new person;
$peoplearray[$name]->name = 'julie' ;
$peoplearray[$name]->foods[$key] = new food;
$peoplearray[$name]->foods[$key]->foodnames[$key] = 'chocolate' ;
$peoplearray[$name]->foods[$key] = new food;
$peoplearray[$name]->foods[$key]->foodnames[$key] = 'coffee' ;
$peoplearray[$name]->foods[$key] = new food;
$peoplearray[$name]->foods[$key]->foodnames[$key] = 'rice' ;
?>

now i need too iterate through all the objects in class food so i can fetch their properties. anyone knows the most effecient way of doing this?

1
  • It's an array. foreach() should suffice. Commented Jul 23, 2012 at 14:01

1 Answer 1

2

Declare a static property in class food and put your food objects in it at construct time :

class food {
  public static $collection = array();
  // other properties ...

  public function __construct() {
    // Stuff
    self::$collection[] = $this;
  }
}

// Create foo objects
$f = new food();

// Iterate
foreach(food::$collection as $foodobj) {
  // Stuff
}
Sign up to request clarification or add additional context in comments.

2 Comments

You should also add a __destruct() implementation to remove the object from the collection. I would index the collection using spl_object_hash($this), and then removing from the collection would be straightforward.
I agree, object destruction should be handled (maybe except if food object will never be destroyed except at script shutdown time ...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.