Codeigniter在函数之间传递变量

时间:2017-05-03 05:31:41

标签: codeigniter

如何在codeigniter控制器中将变量从函数a传递到b。

function a()
{

   $id = $this->input->post('id');

}

我希望函数a的$ id传递给b

function b() 
{

    if($id) 
    {
       .....

    }

}

我该怎么做?

3 个答案:

答案 0 :(得分:2)

创建$ id

public $id = false;

然后使用

function a(){
    $this->id = $this->input->post('id');
}

function b(){
    if($this->id){.....}
}

在控件类

class TestApi extends MY_Controller {
        public function __construct() {
            parent::__construct();
        }

        public t1 = false;

        public function a () {
            $this->t1 = true;
        }

        public function b () {
            a();
            if($this->t1){
                ...
            }
        }
}

或尝试全局变量?但在框架中不是一个好主意

$a1 = 5;
function Test()
{
    $GLOBALS['a1'] = 1;
}

Test();
echo $a1;

在同一类?也许应该检查var或从输入中得到什么?

Class Test{
    public $t = 1;

    public function a(){
        $this->t = 20;
    }

    public function b(){
        echo $this->t;
    }

}

$TestClass = new Test;

echo $TestClass->t;
echo "-";
echo $TestClass->a();
echo ">";
echo $TestClass->t;

答案 1 :(得分:0)

function a(){
    $id = $this->input->post('id');
    $this->b($id);

}

function b($id){
    if ($id) {
        //....
    } else {
        //.....
    }
}

答案 2 :(得分:0)

我使用了$this->session->set_userdata('a', $a); to pass the variable and it can be accessed by all method within the controller. to access it i used $b = $this->session->userdata('a');

感谢所有帮助:D