【问题标题】:How do I get the value of a variable in a function inside a private function in a class?如何在类的私有函数中获取函数中变量的值?
【发布时间】:2012-09-15 07:51:43
【问题描述】:

我有一个像下面这样的 PHP 类

<?php
class Test{
  var $conf = array('a' => 1, 'b' => 2, c => 3);

  private function do_something(){
    // Do something Here
    function do_something_else(){
      // How to get the variable value for $conf ???? o.O
    }
  }
}
?>

我想在函数do_something_else() 中访问$conf。在上层函数中,我可以以$this-&gt;conf 访问它,但我猜$this 在内部函数中不可用。访问该函数内的变量的最佳方法是什么?

我无法传递值,因为该函数将由 WordPress CMS 中的内置函数调用,因此此处不能选择传递参数。

【问题讨论】:

  • 请不要。嵌套函数可能看起来干净,但事实并非如此。嵌套函数与普通函数相同(即它们是全局函数),但仅在调用父函数时才定义。再说一遍,请不要。

标签: php class function variables


【解决方案1】:

我相信你需要的是匿名函数,这里有一些解决方案。 你可以在 PHP 5.3 中做:

 class Test{
    var $conf = array('a' => 1, 'b' => 2, 'c' => 3);

    private function do_something(){
        // Do something Here
        $that = $this;
        $do_something_else = function() use($that) {
            echo $that->conf;
        };

        $do_something_else();   
    }
}

或直接在anonymous 函数上使用$this,但仅限PHP 5.4。

【讨论】:

  • +1 匿名函数闭包,据我所知,是实现他想要的唯一方法。
  • 这看起来很有希望,我正在检查它,感谢您的回复:)
【解决方案2】:

为什么不保持简单

<?php
class Test{
  private $conf;

  private function _construct()
  {
     $this->conf = array('a' => 1, 'b' => 2, c => 3);
  }
  private function do_something_else(){
      // How to get the variable value for $conf ???? o.O
      // NOW THIS BIT IS EASY $this->conf;
  }
  private function do_something(){
    // Do something Here

  }
}
?>

【讨论】:

  • ...除非你 afaik 不能使用 do_something_else() 作为不知道 Test 类的回调。
  • @JoachimIsaksson - 问题没有具体说明。即便如此使用一个接口。更简单、更容易理解。
  • 问题指出该函数将从内置的 Wordpress 函数中调用,这将需要更改 Wordpress 以适应界面或制作额外的“桥代码”层。从长远来看,也许会更好,但不是没有自己痛苦的解决方案。
  • @JoachimIsaksson - 当然 - 但 Wordpress 是开源的,需要人们改进它。 (但恕我直言,Wordpress 是 c**p)
猜你喜欢
  • 2018-12-23
  • 2013-03-23
  • 1970-01-01
  • 2012-08-02
  • 2017-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多