You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CI_Controller出现“无法在写入上下文使用函数返回值”错误求助

解决你的CI_Controller子类致命错误问题

嘿,这个错误的根源其实很明显,咱们马上就能搞定!

错误原因分析

你看到的 Fatal error: Can't use function return value in write context 错误,是因为在index方法里写了一行错误的数组赋值代码:

$data('main_content') = 'cart';

在PHP中,圆括号()会被解析为调用函数的语法,这里PHP会误以为你要调用一个名为$data的函数,然后试图给这个函数的返回值赋值——但函数返回值是不能被直接赋值的,这就触发了这个致命错误。

正确的数组键值对赋值应该使用方括号[],所以这行代码要改成:

$data['main_content'] = 'cart';

额外优化提示(非当前错误,但能完善功能)

另外,你的add方法里只是构造了商品数据数组,但没有调用CodeIgniter的购物车类方法来实际添加商品到购物车,建议在数组构造完成后加上:

$this->cart->insert($data);

这样才能真正把商品加入购物车哦。

修正后的完整代码

<?php 
class Cart extends CI_Controller{ 
    public $paypal_data = ''; 
    public $tax; 
    public $shipping; 
    public $total =0; 
    public $grand_total; 
    //cart index 
    public function index(){ 
        //load view 
        $data['main_content'] = 'cart'; 
        $this->load->view('layouts/main', $data); 
    }//end function 
    //add to Cart 
    public function add(){ 
        //item data in a array construct 
        $data = array(
            'id'=> $this->input->post('item_number'), 
            'qty'=> $this->input->post('qty'), 
            'price'=> $this->input->post('price'), 
            'name'=> $this->input->post('title')
        );//end statement 
        // 新增:将商品添加到CI购物车
        $this->cart->insert($data);
    }//end function 
}//end class cart 

内容的提问来源于stack exchange,提问作者Recency

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:43:41