如何将$ this绑定到PHP函数? [英] How to Bind `$this` to a PHP Function?
问题描述
使用JavaScript,我们可以执行以下操作将范围绑定到所需的函数:
As of JavaScript, we can do a thing like this to bind a scope to the desired function:
function myFunction() {
alert(this.foo);
}
var MyClass = function() {
this.foo = 1;
};
var c = new MyClass();
myFunction.call(c); // `1`
我想用PHP做同样的事情。目前,我认为工作成功是这样的,但这仅适用于匿名函数:
I want to do the same thing using PHP. Currently, what I see working successfully is like this, but this only applies to anonymous functions:
$my_function = function() {
var_dump($this->foo);
};
class MyClass {
public $foo = 1;
};
$c = new MyClass();
Closure::bind($my_function, $c)();
这不起作用:
function my_function() {
var_dump($this->foo);
}
class MyClass {
public $foo = 1;
};
$c = new MyClass();
Closure::bind('my_function', $c)(); // :(
call_user_func([$c, 'my_function']); // :(
推荐答案
如果您使用的是PHP 7.1+,则可以使用 Closure :: fromCallable
(请参见 PHP:类型提示-`Closure`和`Callable`之间的区别有关差异的一些信息):
If you're using PHP 7.1+, you can convert any PHP callable into a Closure
using Closure::fromCallable
(see PHP: Type hinting - Difference between `Closure` and `Callable` for some information about the difference):
$closure = Closure::fromCallable('my_function');
此时,您可以 bind
您的对象实例并执行:
at which point you can bind
your object instance to it and execute:
Closure::bind($closure, $c)();
这篇关于如何将$ this绑定到PHP函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!