Jump to content

[SOLVED] I need an array of classes... !? :-(


alanlee79

Recommended Posts

I hope anyone here can help me... my source is driving me crazy *lol*

 

I made a "simple" example so that maybe everyone can see my proplem:

 

1. Class

class Fish
{
protected $myName;

public function setName($name)
{
	$this->myName = $name;
}

public function getName()
{
	return $this->myName;
}
}

2. Class

class Aquarium
{

public function getAllFishes()
{
	$allfishes[] = array();

	$obj1 = new Fish();
	obj1->setName("First Fish");
	$allfishes[] = $obj1;

	$obj1 = new Fish();
	obj1->setName("Second Fish");
	$allfishes[] = $obj1;

	$obj1 = new Fish();
	$obj1->setName("Third Fish");
	$allfishes[] = $obj1;		

	return $allfishes;
}

}

No I wanna create a new "Aquarium" ... thats easy *smile*

 

$MyAquarium = new Aquarium();

 

But now comes the problem, I wanna give out all the Fishes names :-(

 

My try:

$allFishes = $MyAquarium->getAllFishes();

foreach ($allFishes as $singleFish){
echo $singleFish->getName();
}

I get following error:

 

Fatal error: Call to a member function getName() on a non-object

 

Help...

 

I see the problems starts in the Class Aquarium, where I wanna create a Array and put in the Class(es)...

Link to comment
https://forums.phpfreaks.com/topic/181636-solved-i-need-an-array-of-classes/
Share on other sites

You're receiving that error because of this line: $allfishes[] = array(); In that line you're not making $allfishes an array, rather you're making the first element of $allfishes and array. Just remove that line (because it's not even required) and you should be fine.

 

Edit: You're also missing a $ on this line ( and the other line like this ):

 

obj1->setName("First Fish");

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.