0

As my title, I tried call that method but I got an error:

Fatal error: Call to a member function post() on a non-object in C:\xampp\htdocs\cifirst\application\modules\front\controllers\shopping.php on line 11

If I create a controller not in module, that method I can use very easy but in this case can not (everything code in method below can not run). This is my code:

 public function add_to_cart() {
  $data = array(
   'id' => $this->input->post('productId'), // line 11
   'name' => $this->input->post('productName'),
   'price' => $this->input->post('productPrice'),
   'qty' => 1,
   'options' => array('img' => $this->input->post('productImg'))
  );

  $this->load->library('MY_Cart');
  $this->cart->insert($data);

  //redirect($_SERVER['HTTP_REFERER']);
  //echo $_POST['productId'].'-'.$_POST['productName'];
 }

And this code doesn't work too:

public function __construct() {
    $this->load->library('cart');
    $this->load->helper('form');
}

I'm using XAMPP 1.8.1, CodeIgniter 2.1.3 and newest MX. Please help me!

4

2 回答 2

2

当您在控制器、模型和视图之外使用 CodeIgniter 函数时,您需要首先获取 Codeigniter 的实例。

class MyClass {
    private $CI;

    function __construct() {
        $this->CI =& get_instance();
        $this->CI->load->library('cart');
        $this->CI->load->helper('form');
    }

    public function someFunction() {
        $var = $this->CI->input->post("someField");
    }
}
于 2013-07-13T03:33:29.320 回答
1

如果你打电话:

$this->input->post('productId');

在控制器内部,问题在于您的构造函数声明或类名您的构造部分应包含如下代码:

Class Home extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->CI->load->library('cart');
        $this->CI->load->helper('form');
    }


     public function add_to_cart() 
     {
          $data = array(
                  'id' => $this->input->post('productId'), // line 11
                  'name' => $this->input->post('productName'),
                  'price' => $this->input->post('productPrice'),
                  'qty' => 1,
                  'options' => array('img' => $this->input->post('productImg'))
                  );


      }
}

如果您从辅助函数或任何其他类调用它会正常工作,而不是您应该执行以下操作:

  function __construct()
  {
        parent::__construct();
        $this->CI->load->library('cart');
        $this->CI->load->helper('form');

        $this->CI =& get_instance();
  } 


  public function add_to_cart() 
  {
     $data = array(
        'id' => $this->CI->input->post('productId'), // line 11
        'name' => $this->CI->input->post('productName'),
        'price' => $this->CI->input->post('productPrice'),
        'qty' => 1,
        'options' => array('img' => $this->CI->input->post('productImg'))
        );
 }
于 2013-07-13T04:11:32.880 回答