Iterating an object with an array member
Posted: Thu Jul 14, 2011 11:45 am
I have a strange problem. I have an object that has an array as a member. When I try to use a foreach loop to iterate through the object members, I have an odd occurrence at the array: is_array() does not seem to recognize that the member is an array. I present the following snippet:
This produces the following outout:
I was hoping the is_array function would allow me to go into the second foreach, thus printing the elements of the array. Can anyone explain why the is_array() function seems to not recognize $_arr as an array? Thanks in advance!
Code: Select all
<?php
class TryObjectIteration
{
private $_int;
private $_str;
private $_arr = array();
public function __constructor()
{}
public function set_privates()
{
$this->_int = 55;
$this->_str = 'I am a string';
$this->_arr = array ( 'color' => 'red', 'size' => 9, 'valid' => true );
}
public function print_object()
{
echo '<p>';
foreach ( $this as $key => $value )
{
echo "$key => $value<br />";
if ( is_array ( $key ) )
{
foreach ( $key as $key2 => $value2 )
{
echo "\t$key2 => $value2<br />";
}
}
}
echo '</p>';
}
}
$myObj = new TryObjectIteration();
$myObj->set_privates();
$myObj->print_object();
?>
Code: Select all
_int => 55
_str => I am a string
_arr => Array