Put objects into an array and get them

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
michel77
Forum Newbie
Posts: 17
Joined: Sun Nov 06, 2005 4:57 am

Put objects into an array and get them

Post 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
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post 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;
michel77
Forum Newbie
Posts: 17
Joined: Sun Nov 06, 2005 4:57 am

Post by michel77 »

Thanks for correction. The problem stays, the array key can not be put into a variable (it seems so).
Post Reply