Php 在模型中的函数之间传递变量

Php 在模型中的函数之间传递变量,php,codeigniter,model,Php,Codeigniter,Model,我在模型中有这样的功能 function news() { $data = array( 'title' => $this->input->post('title'), 'date' => $this->input->post('date'), 'newstext' => $this->input->post('newstext'), ); $this->db-

我在模型中有这样的功能

function news() 
{
    $data = array(
        'title' => $this->input->post('title'),
        'date'  => $this->input->post('date'),
        'newstext' => $this->input->post('newstext'),
    );
    $this->db->insert('news', $data);
}

我想在同一个模型的另一个函数中使用这个
$data['title']
。如何做到这一点?

首先,我认为最好将输入值存储在controller中,而不是模型中,以遵循MVC模式,这样您的模型中只有与数据库相关的操作,然后,您可以从控制器调用该函数和另一个函数,并将存储在控制器中的相同输入值传递给这两个函数。

最简单的方法是:

在模型类定义之后声明一个全局变量

例如

class ModalName extends CI_Model()
{
    public $title;

    function news() 
    {
        $data = array(
            'title' => $this->input->post('title'),
            'date'  => $this->input->post('date'),
            'newstext' => $this->input->post('newstext'),
        );
        $this->db->insert('news', $data);
        $this->title = $data['title'];
    }
}
然后


$this->title
将在模型类中的每个函数中可用。

您应该让控制器创建
$data
数组,并将其传递给两个模型函数。