如何将$ this绑定到PHP函数? [英] How to Bind `$this` to a PHP Function?

查看:109
本文介绍了如何将$ this绑定到PHP函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用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+,则可以使用闭包 http://php.net/manual/zh-CN/closure.fromcallable.php rel = nofollow noreferrer> 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)();

请参见 https:// 3v4 l.org/aEnSI

这篇关于如何将$ this绑定到PHP函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆