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

馋奶兔 提交于 2019-12-24 11:15:22

问题


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.


回答1:


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

}



回答2:


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.



来源:https://stackoverflow.com/questions/8275294/how-to-access-variables-from-other-methods-inside-the-same-class-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!