Adding a custom object to an array

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
Hey all,

Anyone have any idea what im doing wrong here:

 $image = new Image();
 $this->mImages[$this->mImageCount] = $image;

where Image is a custom class and mImages is an array declared as
$this->mImages = array();

Whats happening is im executing this function
    function GetImage($imageIndex)
      return $this->mImages[$imageIndex];


and then trying to call a member function on the returned value
$image = $album->GetImage(1);
$imageId = $image->GetImageId();

and im getting this error" Fatal error: Call to a member function on a
non-object in
on line 30"

Any idea why i cant add a custom object to an array then pull it back
out and call a method?

Re: Adding a custom object to an array

Areric wrote:
Quoted text here. Click to load it


class A{
 var $elements = array();
 var $count;
 function A(){
  $this->count = 0;
 function add_element($text){
  $object = new B($text);
  $this->elements[$this->count] = $object;
 function return_element($int){
  return $this->elements[$int];
class B{
 var $text;
 function B($var){
  $this->text = $var;
 function display(){
  echo $this->text;

$test = new A();
$test->add_element("This works");
$test->add_element("Several times even");
$object = $test->return_element(0);
$object2 = $test->return_element(1);

Outputs: "This worksSeveral times even"

So, I think the problem would be elsewhere.
What do you see if you var_dump() your $album, or print_r($album->mImages),
before getting the image out? Does it really contain the object?

Maybe the Image class is only declared after the album has already tried to
add the images?

What happens if in the method you add the images, instead of
$this->mImages[$this->mImageCount] = $image;
return is_object($image):

Does it return false or true?

Rik Wasmus

Re: Adding a custom object to an array


THanks for the help you were right the problem was elsewhere. For some
reason my mImageCount wasnt getting initalized properly. So when i
added my first image it was adding it to a index with no value, where
when i tried to reference it i was referencing index 0. The weird thing
was i had the mImageCount = 0 in the constructor.

Oh well i fixed it by initalizing the variable where it was declared
instead of the constructor.

Re: Adding a custom object to an array

Areric wrote:
Quoted text here. Click to load it

Euhm, you've lost me.
If you initialize mImageCount = 0;
Add an object by $this->mImages[$this->mImageCount] = $image;
Surely it would be at index 0....
Or were you incrementing mImageCount beforehand?

Rik Wasmus

Site Timeline