Codeigniter 在视图中传递对象

Codeigniter passing objects within views

我正在从控制器文件加载一个视图,该视图加载另一个视图,最后一个如下所示,

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);

我在这里使用对象而不是数组作为视图之间的传递变量。但如果我使用数组,它工作正常。

上面的代码抛出如下错误,

Message: Attempt to assign property of non-object

如有任何帮助,我们将不胜感激。

是的,您仍然可以传递对象,但不是 'first level',您需要将要传递的对象包装在一个数组中。

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

这是因为当 CodeIgniter 初始化视图时,它会检查第二个 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;
}

反过来,将您的初始 $data 变成:

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

Array ( [device_name] => Apple )

因此,为避免这种情况,请将您的对象嵌套在 array() 中,这样可以避免被转换。