Raja
Raja

Reputation: 3627

Codeigniter passing objects within views

I am loading a view from a Controller file and that View loads another view which a final one as below,

First view Call : 

    Controller: device.php

        public function device_name(){
           $data = new stdClass;
           $data->device_name = "Apple";
           $this->load->view('apple_device',$data);
        }

Second view call :

    View: In apple_device.php

       $device_name->count = 123;
       $this->load->view('device_counts',$device_name);

I am using object here instead of an array as a passing variable between views. But if i use array, it works fine.

And the above code throwing error as like below,

Message: Attempt to assign property of non-object

Any help would be appreciated.

Upvotes: 2

Views: 1924

Answers (1)

MackieeE
MackieeE

Reputation: 11862

Yes, you may still pass through objects, but not at the 'first level', you'll need to wrap the object you want to pass through inside an array.

public function device_name(){
    $mobiles = new stdClass;
    $mobiles->device_name = "Apple";
    $data = array( "mobiles" => $mobiles );
    $this->load->view('apple_device',$data);
}

This is because when CodeIgniter will initialize the view, it will check the contents of the second view() parameter. If it's an object - it'll cast it to an array via get_object_vars() (See github link)

protected function _ci_object_to_array($object)
{
    return is_object($object) ? get_object_vars($object) : $object;
}

Which will in turn, turn your initial $data into:

$data = new stdClass;
$data->device_name = "Apple";
$example = get_object_vars( $data );
print_r( $example );

Array ( [device_name] => Apple )

Thus to avoid this, nest your object inside an array() which will avoid being converted.

Upvotes: 1

Related Questions