【问题标题】:PHP: How do I access a local varibale of a function in class from another functionPHP:如何从另一个函数访问类中函数的局部变量
【发布时间】:2014-03-13 12:11:12
【问题描述】:

所以我有一个 php 类,我有一个小小的咆哮。想象一个如下所示的类

<?php
class Foo
{
   public function __construct()
  {
     $this->bar1();
  }
  public function bar1()
  {
    $myvar = 'Booya!';

   return 'Something different';
  }
  public function bar2()
  {
    //get value of $myvar from bar1()
  }
}
$new_foo = new Foo();
$new_foo->bar2();
?>

问题是, 如何从bar1() 访问变量$myvar,记住bar1() 返回的东西不同。

【问题讨论】:

  • 将其保存为类属性,例如$this-&gt;myvar?

标签: php function variables scope


【解决方案1】:

你会做这样的事情......一切都已经通过代码旁边的cmets解释了。

<?php
class Foo
{
    private $myvar; //<---- Declare the variable !
    public function __construct()
    {
        $this->bar1();
    }
    public function bar1()
    {
        $this->myvar = 'Booya!'; //<---- Use this $this keyword

        //return 'Something different';//<--- Comment it.. Its not required !
    }
    public function bar2()
    {
        return $this->myvar; //<----- You need to add the return keyword
    }
}
$new_foo = new Foo();
echo $new_foo->bar2(); //"prints" Booya!

【讨论】:

    【解决方案2】:
    <?php
    class Foo
    {
      var $myvar;
      public function __construct()
      {
         $this->bar1();
      }
      public function bar1()
      {
        $this->myvar = 'Booya!';
    
       return 'Something different';
      }
      public function bar2()
      {
        //get value of $myvar from bar1()
        echo $this->myvar;
      }
    }
    $new_foo = new Foo();
    $new_foo->bar2();
    ?>
    

    你应该先将它设置为类变量,然后使用$this访问它

    【讨论】:

      【解决方案3】:

      你不能直接这样做,只有你可以在不改变 bar1() 返回值的情况下创建一个 用于保存此数据值的类变量 在类定义中添加

      private $saved_data;
      

      在 bar1() 中:

      $myvar = 'Booya!';
      $this->saved_data = $myvar;
      

      在 bar2() 中

      $myvar_from_bar1 = $this->saved_data
      

      【讨论】:

        【解决方案4】:

        使用类变量,例如:

        $this->myvar = 'Booya!';
        

        现在变量 myvar 将存储在类中,并且可以在其他方法中请求或更改。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-09-28
          相关资源
          最近更新 更多