如何从PHP中同一类中的其他方法访问变量


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

我试过了,但无法使它工作:

class Profile extends CI_Controller {
   public function index() {
      $foo = 'bar';
   }
   public function form_submit() {
      echo $this->index()->foo;
   }
}

我知道我可以通过在类级别的所有方法之外声明变量并将其声明为公共来使类中的所有方法都可以访问它。但是这里我需要在其中一个方法中声明变量

如果你在方法中声明它,除非你返回值,否则你就不走运了。

class Profile {
    public function index() {
      $foo = 'bar';
      return $foo;
    }
    public function form_submit() {
      echo $this->index();
    }
}

一个更好的选择可能是将它声明为一个对象变量(你所说的"在类级别"),但声明它是私有的。

class Profile {
   private $foo;
   public function index() {
      $this->foo = 'bar';
   }
   public function form_submit() {
      echo $this->foo;
   }
}

不!

类是对共享状态进行操作的方法的集合。共享状态通过实例化类的对象来创建。

由于index()form_submit()共享$foo状态,您的代码应该是这样的:

class Profile extends CI_Controller {
   private
     $foo;
   public function index() {
      $this->foo = 'bar';
   }
   public function form_submit() {
      echo $this->foo;
   }
}

在某些情况下,注册表模式可能会有所帮助。但不是你的情况。

或者,您可以将$foo提升到全局作用域。但是由于这是非常糟糕的风格,我不愿意提供代码示例。对不起。