Accessing methods of an array of objects

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
cosmicstring
Forum Newbie
Posts: 1
Joined: Thu May 20, 2004 1:06 pm

Accessing methods of an array of objects

Post by cosmicstring »

I have a class, that for one of its properties has an array.

In that array I am storing a number of other objects.

I can loop through the array of objects no problem using foreach, but when I try to access a method of one of the objects it gives me a "Call to a member function on a non-object in" error.

Any ideas how I access an object that's been stored in an array?

Thanks
User avatar
launchcode
Forum Contributor
Posts: 401
Joined: Tue May 11, 2004 7:32 pm
Location: UK
Contact:

Post by launchcode »

Depends on your code, but the following works for me:

Code: Select all

<?php
class ObjectA
{
	function test ()
	{
		echo "Hello from Object A";
	}
}

class ObjectB
{
	function test ()
	{
		echo "Hello from Object B";
	}
}

class ObjectC
{
	function test ()
	{
		echo "Hello from Object C";
	}
}

$object_array[] = new ObjectA();
$object_array[] = new ObjectB();
$object_array[] = new ObjectC();

$object_array[1]->test();
?>
Post Reply