Welcome Guest, Not a member yet? Register   Sign In
Adding property to an object
#1

[eluser]Marcelo Kanzaki[/eluser]
Sorry, i don't know if this is the right place to ask this. But i really could use some help.

I'm using CI with PHP5 and when i went testing on the server, some bugs happened.

I have this function in on of my models and i didn't know that php4 doesn't support adding properties to objects the way i did. Can someone tell me how to get around this problem?

Code:
function find_ ($page_id)
    {
        $this->db->where('page_parent_id', $page_id);
        $this->db->order_by('page_created', 'DESC');
        $query = $this->db->get('fala_pages');
        
        foreach ($query->result() as $row)
        {
            $row->subpages = count( $this->find_($row->page_id) );
        }
        
        return $query->result();
    }
#2

[eluser]Phil Sturgeon[/eluser]
Code:
function find_ ($page_id)
    {
        $this->db->where('page_parent_id', $page_id);
        $this->db->order_by('page_created', 'DESC');
        $query = $this->db->get('fala_pages');
        
        foreach ($query->result() as &$row)
        {
            $row->subpages = count( $this->find_($row->page_id) );
        }
        
        return $query->result();
    }

Notice the & before the $row in your foreach. This means the $row is passed by refference and not by value, meaning you can modify that variable and change the original value.
#3

[eluser]xwero[/eluser]
You need to not only bind the new property to the row but you have to bind it to the array too.
Code:
$rows = $query->result();

foreach ($rows as $key=>$row)
{
   $rows[$key]->subpages = count( $this->find_($row->page_id) );
}
// php5 only
$rows = $query->result();

foreach ($rows as &$row)
{
   $row->subpages = count( $this->find_($row->page_id) );
}
#4

[eluser]Marcelo Kanzaki[/eluser]
Thank you both so much for the fast and helpful reply. Problem solved.




Theme © iAndrew 2016 - Forum software by © MyBB