2016-07-21

This is not making any sense to me—perhaps it makes sense to someone else here.

I have a class called Event which represents, well, an event. It has three properties: an id, a description, and a time. The time property is itself an object of type DateTime.

A third class, Member, has a property called Events, which is populated with an array of Event objects. A simple var_dump of a Member object thus looks like this, leaving out some more properties that aren’t relevant here:

Within the Member class, there is a function to list all events in tabular form, formatEventsAsTable() which, in a nutshell does this:

As far as I can tell, this should work: in the loop, $event is an Event object (verifiable by var_dumping it during the loop) with a property time that is a DateTime object and should thus have the format function. But it doesn’t work.

For some reason, the DateTime object gets force-cast to a string, and I get this error message:

Fatal error: Uncaught Error: Call to a member function format() on string in /path/to/file/class.Member.php:116

This is most unexpected to me: var_dump $event shows the property time to be a DateTime object. But var_dump $event->time yields:

Even more bizarrely: if instead I put the actual code in the foreach loop inside the Event class, adding a function Event::formatAsTableRow() that calls $this->time->format('j/n Y'), and then simply call that function in the foreach loop in Member::formatEventsAsTable()… then it works just fine.

So why can I access a DateTime object as such from within the class where it’s a property, but not from a function in a different class? Why does it get force-cast (?) to a string there?

Show more