【问题标题】:Closures in a class and protected methods类中的闭包和受保护的方法
【发布时间】:2016-02-03 17:45:01
【问题描述】:

我不清楚以下是否可行:

class Sample {
    private $value = 10;

    public function something() {
        return function() {
            echo $this->value;
            $this->someProtectedMethod();
        }
    }

    protected function someProtectedMethod() {
        echo 'hello world';
    }
}

我使用的是 PHP 5.6,它将运行的环境是 5.6。我不确定两件事,这个范围。以及是否可以在闭包函数中调用受保护的方法、私有方法和私有变量。

【问题讨论】:

    标签: php closures


    【解决方案1】:

    问题 #1 是一个简单的语法错误:

        return function() {
            echo $this->value;
            $this->someProtectedMethod();
        };
    

    (注意分号)

    现在,当您调用something()...时,此代码将返回实际函数。它不会执行该函数,因此您需要将该函数分配给一个变量。您必须显式调用该变量作为函数来执行它。

    // Instantiate our Sample object
    $x = new Sample();
    // Call something() to return the closure, and assign that closure to $g
    $g = $x->something();
    // Execute $g
    $g();
    

    然后您会遇到范围问题,因为在调用 $g 时,$this 不在函数范围内。您需要将我们实例化的 Sample 对象绑定到闭包,以提供$this 的作用域,因此我们实际上需要使用

    // Instantiate our Sample object
    $x = new Sample();
    // Call something() to return the closure, and assign that closure to $g
    $g = $x->something();
    // Bind our instance $x to the closure $g, providing scope for $this inside the closure
    $g = Closure::bind($g, $x)
    // Execute $g
    $g();
    

    编辑

    Working Demo

    【讨论】:

      猜你喜欢
      • 2017-06-14
      • 2020-11-07
      • 1970-01-01
      • 2020-05-02
      • 2020-03-31
      • 1970-01-01
      • 2011-02-03
      • 1970-01-01
      • 2016-02-19
      相关资源
      最近更新 更多