Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variables of a function to other function in a controller in codeigniter?

Tags:

codeigniter

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?

like image 699
cabita Avatar asked Nov 20 '11 15:11

cabita


2 Answers

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

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.

like image 106
Rooneyl Avatar answered Sep 25 '22 19:09

Rooneyl


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

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

function myOtherFunction($variable){
    // $variable passed from myFunction() is equal to 'hello';
}
like image 38
Colin Brock Avatar answered Sep 24 '22 19:09

Colin Brock