user967451
user967451

Reputation:

How to access variables from other methods inside the same class in PHP?

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.

Upvotes: 3

Views: 5569

Answers (2)

SteAp
SteAp

Reputation: 11999

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.

Upvotes: 0

Trott
Trott

Reputation: 70065

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;
   }

}

Upvotes: 2

Related Questions