alanlee79 Posted November 15, 2009 Share Posted November 15, 2009 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)... Quote Link to comment https://forums.phpfreaks.com/topic/181636-solved-i-need-an-array-of-classes/ Share on other sites More sharing options...
Alex Posted November 15, 2009 Share Posted November 15, 2009 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"); Quote Link to comment https://forums.phpfreaks.com/topic/181636-solved-i-need-an-array-of-classes/#findComment-958051 Share on other sites More sharing options...
alanlee79 Posted November 15, 2009 Author Share Posted November 15, 2009 well... :-) thanks a lot... it works... Quote Link to comment https://forums.phpfreaks.com/topic/181636-solved-i-need-an-array-of-classes/#findComment-958053 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.