回调函数中的$this
我想知道为什么这有效:
class Foo {
public function doSomethingFunny($subject) {
preg_replace_callback(
"#pattern#",
array($this, 'doX'),
$subject
);
}
private function doX() {
echo 'why does this work?';
}
}
为什么回调仍然在 $this 的上下文中?我希望它只允许公共方法。我错过了回调工作原理的一些基本内容。
I would like to know why this works:
class Foo {
public function doSomethingFunny($subject) {
preg_replace_callback(
"#pattern#",
array($this, 'doX'),
$subject
);
}
private function doX() {
echo 'why does this work?';
}
}
Why is the callback still within the context of $this? I would expect it the allow only public methods. I'm missing something fundamental in how the callback works.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
preg_replace_callback() 中的回调参数允许调用方法,并允许传递数组来告诉方法回调的上下文。它不仅是$this,还可以是任何对象变量。
在上面的例子中,如果 Foo::bar() 是私有的,那将不起作用。但是,在您原来的情况下,由于使用了与私有方法位于同一上下文中的 $this ,私有方法仍然被触发。
The callback parameter in preg_replace_callback() allows for the calling of a method, and allows for the passing of an array to tell the method the context of the call back. It's not only $this, but also any object variable.
In the example above, if Foo::bar() is private, that would not work. However, in your original case, the private method is still triggered because of the use of $this which is in the same context as the private method.
如果它在同一个类中,那么它就在相同的范围/上下文中($this)。
if it's in the same class it's in the same scope/context ($this).
我相信这暗示回调在当前范围内执行。
call_user_func
或任何使用回调的函数(例如preg_replace_callback
)旨在以编程方式模拟等效的内联调用。换句话说,它必须以这种方式运行才能提供预期的功能。因此,在以下情况下,无论可见性如何,
Foo->A()
和Foo->B()
的行为方式应该相同:没有明确记录不过,这会很方便。
I believe it is implied that a callback executes in the current scope.
call_user_func
, or any function that uses a callback (such aspreg_replace_callback
) is intended to programatically emulate the equivalent in-line call. In other words, it must behave that way in order to provide the intended functionality.Therefore in the following case
Foo->A()
andFoo->B()
should behave the same way, regardless of visibility:It isn’t explicitly documented though, which would be handy.