为什么将闭包从一个 class 传递到另一个并从第二个 class 调用它执行第一个 class 的代码?
Why exactly does passing a closure from one class to another and calling it from the second class execute code from the first class?
很难为这个问题想出一个标题,但基本上这里是代码:
<?php
class Sub {
protected $closure;
public function setClosure($closure) {
$this->closure = $closure;
}
public function callClosure() {
$this->closure->__invoke();
}
protected function outcome() {
echo 'calling from sub';
}
}
class Main {
public function __construct() {
$this->sub = new Sub();
}
public function start() {
$this->sub->setClosure(function() {
$this->outcome();
});
$this->sub->callClosure();
}
protected function outcome() {
echo 'calling from main';
}
}
$main = new Main();
$main->start();
它的结果是calling from main
。然而,这正是我想要的,因为我将处理这种行为并且我不完全理解为什么它以这种方式工作我想要一些澄清。
在编写代码之前,我希望它从 Sub
class 而不是 Main
class 调用 outcome
方法。闭包是否使用其定义范围内的 $this
?如果出于某种原因,我希望它在调用它的范围内使用 $this
怎么办?
根据 php anonymous functions 手册,它工作正常,因为
The parent scope of a closure is the function in which the closure was
declared (not necessarily the function it was called from)
在 php 中,此匿名函数实现为 Closure class。
正如 Mark Baker 所说,当您在 Main
class 中创建闭包时,您会自动获得此绑定对象和此 class 范围。
The “bound object” determines the value $this will have in the
function body and the “class scope” represents a class which
determines which private and protected members the anonymous function
will be able to access. Namely, the members that will be visible are
the same as if the anonymous function were a method of the class given
as value of the newscope parameter.
在你的情况下,这个 class 是 Main
而不是 Sub
很难为这个问题想出一个标题,但基本上这里是代码:
<?php
class Sub {
protected $closure;
public function setClosure($closure) {
$this->closure = $closure;
}
public function callClosure() {
$this->closure->__invoke();
}
protected function outcome() {
echo 'calling from sub';
}
}
class Main {
public function __construct() {
$this->sub = new Sub();
}
public function start() {
$this->sub->setClosure(function() {
$this->outcome();
});
$this->sub->callClosure();
}
protected function outcome() {
echo 'calling from main';
}
}
$main = new Main();
$main->start();
它的结果是calling from main
。然而,这正是我想要的,因为我将处理这种行为并且我不完全理解为什么它以这种方式工作我想要一些澄清。
在编写代码之前,我希望它从 Sub
class 而不是 Main
class 调用 outcome
方法。闭包是否使用其定义范围内的 $this
?如果出于某种原因,我希望它在调用它的范围内使用 $this
怎么办?
根据 php anonymous functions 手册,它工作正常,因为
The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from)
在 php 中,此匿名函数实现为 Closure class。
正如 Mark Baker 所说,当您在 Main
class 中创建闭包时,您会自动获得此绑定对象和此 class 范围。
The “bound object” determines the value $this will have in the function body and the “class scope” represents a class which determines which private and protected members the anonymous function will be able to access. Namely, the members that will be visible are the same as if the anonymous function were a method of the class given as value of the newscope parameter.
在你的情况下,这个 class 是 Main
而不是 Sub