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
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");

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.