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

时间:2022-10-06 22:43:04

I have a controller that has the next functions:

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

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 
    }

}

I thanks for your answers. How can I pass variables of a function to other function in a controller of codeigniter?

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

2 个解决方案

#1


5  

Or you can set $variable as an attribute in you class;

或者您可以将$ 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';
    }

}

This way variable will be available to all functions/methods in your controller class. Think OOP not procedural.

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

#2


4  

You need to define a parameter formyOtherFunction and then simply pass the value from myFunction():

您需要定义一个参数formyOtherFunction,然后只需从myFunction()传递值:

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

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

#1


5  

Or you can set $variable as an attribute in you class;

或者您可以将$ 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';
    }

}

This way variable will be available to all functions/methods in your controller class. Think OOP not procedural.

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

#2


4  

You need to define a parameter formyOtherFunction and then simply pass the value from myFunction():

您需要定义一个参数formyOtherFunction,然后只需从myFunction()传递值:

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

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