从类函数中获取变量


Getting variable from class function

是否有一种方法可以在使用该函数后获得在对象函数内设置的变量?
在我的例子中$season array

    class Patch{
       public function display(){
                $season = array(); //Variable for line chart 
       }
    }
$Patch = new Patch();
$Patch->display();
var_dump($Patch->$season());

让变量$season public可见

class Patch {
   public $season = array();
... 

$season存在只有display函数的作用域中。如果你想通过$Patch->season访问它,那么你需要将它声明为类的public属性。

class Patch{
    public $season;
    public function display(){
        $this->season = array(); //Variable for line chart 
    }
}
$Patch = new Patch();
$Patch->display();
var_dump($Patch->season);

其实有很多方法。

1声明变量为类属性(最好的方式)

 class Patch
 {
      private $season;
      public function getSeason () {
           return $this->season;
      }
      public function setSeason ($season) {
           $this->season = $season;
      }
      public function display () {
           echo $this->getSeason();
      }
 }
 $obj = new Patch();
 $obj->setSeason(array());
 $obj->display();
  • 通过方法display()返回变量(也很好,但在某些情况下)
  • 通过引用传递变量。