views:

48

answers:

3

Hi,

For a php project I use a Collection class to handle my objects and lazyloading in Java-like collections.

Now my object has a collection of emailaddresses for example. So I call the getEmailAddresses() function of the object which calls the mapper to return a collection of emailaddresses.

This works fine, but when I do a foreach loop over my collection it returns valid data with the following error in the end:

Fatal error: Call to a member function create() on a non-object in /foo/bar/Collection.php on line 89

It directs to the following function:

public function current()
    {
        if ($this->_collection instanceof Iterator)
            $key = $this->_collection->key();
        else
            $key = key($this->_collection);
        if ($key === null)
            return false;
        $item = $this->_collection[$key];
        if (!is_object($item)) {
            $item = $this->_gateway->create($item);
            $this->_collection[$key] = $item;
        }
        return $item;
    }

This line:

$item = $this->_gateway->create($item);

The _gateway is the adapter the collection uses. Which I don't use and keep it null. Maybe it has something to do with that?

Anybody has some clue? Because everything is functioning as it should, I can read the collectiondata. It's just the error.

A: 

This only means that $this->_gateway is not an object and it should be. It can't be null.

You can change this line:

$item = $this->_gateway->create($item);

to

if(is_object($this->_gateway)) {
  $item = $this->_gateway->create($item);
}

this will fix this error, but can lead to more errors further down, depending on what exactly is $item supposed to be.

Mchl
Yeah, but the strange thing i I use this class for more collections in this project in the same way. It works like a charm.But now it gives this error... it's very strange.
baklap
A: 

Replace

if (!is_object($item))

with

if (!is_object($item) && !is_null($this->_gateway))

This of course only makes sure the code doesn't get called if gateway isn't set, so it doesn't do anything to $item (which might not be what you want).

wimvds
Hmm both answers arent working. I get errors that I try to call methods on a nullobjectIt looks like the mapper appends an object which it shouldnt. As if it appends a null object, but the Collection handles it as an countable value but not as the required object.
baklap
Then the source of your problem is elsewhere, debugging (using xdebug or Zend Debugger) should help to find the cause.
wimvds
A: 

Already got it!

It appears that if the collection requested doesnt have any objects, it just tries to do something.

If I first count the items and compare it to > 0 it doesnt return any errors. This is going to be an issue so I'll update the class to check for it first.

I'm not the only one working with it, this is not an error you would expect.

baklap