将函数的变量传递给codeigniter中控制器中的其他函数?

时间:2011-11-20 15:21:15

标签: codeigniter

我有一个具有下一个功能的控制器:

class controller {

    function __construct(){

    }

    function myfunction(){
        //here is my variable
        $variable="hello"
    }


    function myotherfunction(){
        //in this function I need to get the value $variable
        $variable2=$variable 
    }

}

我感谢您的回答。如何将函数的变量传递给codeigniter控制器中的其他函数?

2 个答案:

答案 0 :(得分:5)

或者您可以将$ variable设置为您的类中的属性;

class controller extends CI_Controller {

    public $variable = 'hola';

    function __construct(){

    }

    public function myfunction(){
        // echo out preset var
        echo $this->variable;

        // run other function
        $this->myotherfunction();
        echo $this->variable;
    }

    // if this function is called internally only change it to private, not public
    // so it could be private function myotherfunction()
    public function myotherfunction(){
        // change value of var
        $this->variable = 'adios';
    }

}

这样,变量将可用于控制器类中的所有函数/方法。认为OOP不是程序性的。

答案 1 :(得分:4)

您需要为myOtherFunction定义参数,然后只传递myFunction()中的值:

function myFunction(){
    $variable = 'hello';
    $this->myOtherFunction($variable);
}

function myOtherFunction($variable){
    // $variable passed from myFunction() is equal to 'hello';
}
相关问题