Michael Grigsby
Michael Grigsby

Reputation: 12163

CodeIgniter grabbing variables from other methods inside the same class

In Ci, how do I grab a variable from another method inside the same class?

Upvotes: 2

Views: 4388

Answers (1)

swatkins
swatkins

Reputation: 13630

You'll have to set it as a class variable and use that.

Something like:

<?php
class Blog extends CI_Controller {

    $my_variable = null;

    function _set_myvariable()
    {
        $this->my_variable = "this variable has a value";
    }

    function get_variable()
    {
            echo $this->my_variable; // outputs NULL
            $this->_set_myvariable();
            echo $this->my_variable; // outputs "this variable has a value"
    }
}
?>

calling the get_variable method will:

  1. Call the _set_myvariable private function (note the "_" starting the function name) that will set the class variable.
  2. Then, it will echo out the value of that variable (which will be "this variable has a value")

Upvotes: 4

Related Questions