CodeIgniter - 无法运行$ this-> input-> post('inputName');在模块化扩展中

时间:2013-07-13 03:03:07

标签: php codeigniter hmvc

作为我的标题,我尝试调用该方法但是我收到了错误:

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

如果我创建一个不在模块中的控制器,那么我可以很容易地使用该方法,但在这种情况下不能(下面方法中的所有代码都无法运行)。这是我的代码:

 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'];
 }

此代码也不起作用:

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

我正在使用XAMPP 1.8.1,CodeIgniter 2.1.3和最新的MX。请帮帮我!

2 个答案:

答案 0 :(得分: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");
    }
}

答案 1 :(得分: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'))
        );
 }