Jump to content

[SOLVED] initialize class attribute as an array;


mbeals

Recommended Posts

In my classes I tend to define an attribute as an array to hold children objects created by the parent object. 

 

I figured declaring the attribute as:

 


protected $attribute = array();

 

would be enough but it's not.  When I initialize the attribute as an array, it doesn't become an array until I put stuff in it.  I checked this by echoing gettype() of the attribute before and after filling it.  Just after initialization, the attribute has type NULL.  I'm guessing this is to save memory, but it's really inconvenient.

 

If I run a foreach on this attribute, I need it to see it as an array with 0 members, so it will just bypass it instead of popping a warning.

 

is there a way around this besides  if($this->attribute) foreach() ?

 

your right.  I had this:

 

foreach($this as $key => $value) $this->$key = $row[$key];

 

 

in my constructor to populate the object variable from a database.  It was resetting every attribute that didn't have an entry in the database to NULL.

 

Changed it to:

foreach($row as $key => $value) $this->$key = $value;

 

and all is well.  Thanks

Archived

This topic is now archived and is closed to further replies.

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