Page 1 of 1

Put objects into an array and get them

Posted: Wed Nov 16, 2005 1:33 pm
by michel77
I have a task: reading / writing xml and working with objects. The only open questions (simply formulated)

Code: Select all

<?php
class Woman{
	private $id;	     // string
	private $hair;
	function getId(){return $this->id;}
}
class Man{
	private $id;	      // string
	private $car;
	function getId(){return $this->id;}
}
class Group {
	private $name;
	private $members = array();            // array of classes woman / man
	public function addMember ($member){ 
		                                                                            // how to add a new member with her - his id ?
		$this->members[$member->id] = $member;       // does not work
	}
}
class World {
	private $group;            // Typ class Group
	private $id;
	private $test_id;
	private $test_member; // woman - man
	public function doit(){	
	$this->test_member = $this->group->members[$this->id];      // how to access a member ?
	$this->test_id= $this->group->members[$this->id]->getId();  // how to access their methods ?	
	}	
}
?>
HawleyJR:Please use tags when Posting PHP Code In The Forums

Posted: Wed Nov 16, 2005 3:06 pm
by Jenk
$member->id; is a 'private' property, which means only the methods within that object can access that property.

For it to work in that fashion, you would require the property to be 'public'

Though it is better practice to have a 'get' function to get the ID instead of directly accessing the property, which you already have. So change to this:

Code: Select all

$this->members[$member->getId()] = $member;

Posted: Wed Nov 16, 2005 3:22 pm
by michel77
Thanks for correction. The problem stays, the array key can not be put into a variable (it seems so).