如何从PHP中的同一类内部的其他方法访问变量? [英] How to access variables from other methods inside the same class in PHP?

查看:67
本文介绍了如何从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;
   }

}



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

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.

推荐答案

如果你在方法中声明它,除非您返回值。

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

}

这篇关于如何从PHP中的同一类内部的其他方法访问变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆