0

我有一个如下的 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
    }
  }
}
?>

我想访问$conf函数内部do_something_else()。在上层函数中,我可以将其作为 访问$this->conf,但我想$this在内部函数中将不可用。访问该函数内的变量的最佳方法是什么?

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

4

2 回答 2

3

我相信你需要的是匿名函数,这里有一些解决方案。您可以在 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();   
    }
}

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

于 2012-09-15T08:09:26.167 回答
1

为什么不保持简单

IE

<?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

  }
}
?>
于 2012-09-15T08:11:24.933 回答