3

I tried this but couldn't get it to work:

class Profile extends CI_Controller {

   public function index() {
      $foo = 'bar';
   }

   public function form_submit() {
      echo $this->index()->foo;
   }

}

I know I can make a variable accessible to all the methods in a class by declaring it outside all the methods at class level and declaring it as public. But here I need to declare the variable inside one of the methods.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • 1
    You can't do it like that, because `$foo` is out of scope; you need to use a class property or a session variable, or do `echo $this->index();` and return `$foo`. You can, of course, make the class property `private`ly scoped, so only the class can access it. – Jared Farrish Nov 26 '11 at 00:09
  • Added the CI tag because controller methods in CodeIgniter work slightly differently from regular PHP class methods, which may or may not affect your question. But what @Jared Farrish said also works. – BoltClock Nov 26 '11 at 00:14

2 Answers2

2

If you are declaring it inside the method, you are out of luck unless you return the value.

class Profile {

    public function index() {
      $foo = 'bar';
      return $foo;
    }

    public function form_submit() {
      echo $this->index();
    }
}

A perhaps better alternative would be to declare it as an object variable (what you describe as "at class level") but declare it private.

class Profile {

   private $foo;

   public function index() {
      $this->foo = 'bar';
   }

   public function form_submit() {
      echo $this->foo;
   }

}
Trott
  • 66,479
  • 23
  • 173
  • 212
  • How about your first example if there is two variables in the `index()` method?! – Shafizadeh Oct 07 '15 at 13:43
  • @Shafizadeh you can only return one variable only, if you have to return multiple variables, then you need return an array/object – rafi Apr 26 '16 at 10:48
0

No! In no case, one can image that accessing a variable in another method is useful or necessary.

A class is a collection of methods which operate on a shared state. The shared state gets created by instantiating an object of a class.

Since index() and form_submit() share the $foo state, your code should read like this:

class Profile extends CI_Controller {

   private
     $foo;

   public function index() {
      $this->foo = 'bar';
   }

   public function form_submit() {
      echo $this->foo;
   }

}

In certain situations, the registry pattern might be helpful. But not in your case.

Alternatively, you could lift $foo into the global scope. But since this is very bad style, I'm not willing to provide a code example. Sorry.

SteAp
  • 11,853
  • 10
  • 53
  • 88