mbeals Posted July 30, 2008 Share Posted July 30, 2008 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() ? Link to comment https://forums.phpfreaks.com/topic/117374-solved-initialize-class-attribute-as-an-array/ Share on other sites More sharing options...
DarkWater Posted July 30, 2008 Share Posted July 30, 2008 It works for me. This code: <?php class foo { protected $foo = array(); public function type() { echo gettype($this->foo); } } $f = new foo(); $f->type(); ?> Prints out "array". Link to comment https://forums.phpfreaks.com/topic/117374-solved-initialize-class-attribute-as-an-array/#findComment-603684 Share on other sites More sharing options...
mbeals Posted July 30, 2008 Author Share Posted July 30, 2008 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 Link to comment https://forums.phpfreaks.com/topic/117374-solved-initialize-class-attribute-as-an-array/#findComment-603746 Share on other sites More sharing options...
DarkWater Posted July 30, 2008 Share Posted July 30, 2008 No problem. Please mark this topic as solved. Link to comment https://forums.phpfreaks.com/topic/117374-solved-initialize-class-attribute-as-an-array/#findComment-603751 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.