大网数据广告活动
PHP 语言与运行手册

ReflectionFunctionAbstract::getClosureThis · 返回闭包内与 $this 对应的对象

· 52CE 我爱测

ReflectionFunctionAbstract::getClosureThis — 返回闭包内与 $this 对应的对象

ReflectionFunctionAbstract::getClosureThis

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::getClosureThis — 返回闭包内与 $this 对应的对象

说明

public function ReflectionFunctionAbstract::getClosureThis(): ?object

如果函数是非静态闭包,获取绑定到闭包内部 $this 的对象。

参数

此函数没有参数。

返回值

返回 Closure 中 $this 所表示的对象实例。如果函数不是闭包或者没有 $this,则返回 null。

示例

示例 #1 Example showcasing difference between ReflectionFunctionAbstract::getClosureCalledClass(), ReflectionFunctionAbstract::getClosureScopeClass(), and ReflectionFunctionAbstract::getClosureThis() with a closure in the object context

<?php

class A
{
    public function getClosure()
    {
        var_dump(self::class, static::class);

        return function() {};
    }
}

class B extends A {}

$b = new B();
$c = $b->getClosure();
$r = new ReflectionFunction($c);

var_dump($r->getClosureThis()); // $this === $b, since a non-static closure take the object context
var_dump($r->getClosureScopeClass()); // Corresponds to the self::class resolution inside a closure
var_dump($r->getClosureCalledClass()); // Corresponds to the static::class resolution inside a closure

?>

以上示例会输出:

string(1) "A"
string(1) "B"
object(B)#1 (0) {
}
object(ReflectionClass)#4 (1) {
  ["name"]=>
  string(1) "A"
}
object(ReflectionClass)#4 (1) {
  ["name"]=>
  string(1) "B"
}

示例 #2 Example showcasing difference between ReflectionFunctionAbstract::getClosureCalledClass(), ReflectionFunctionAbstract::getClosureScopeClass(), and ReflectionFunctionAbstract::getClosureThis() with a static closure without an object context

<?php

class A
{
    public function getClosure()
    {
        var_dump(self::class, static::class);

        return static function() {};
    }
}

class B extends A {}

$b = new B();
$c = $b->getClosure();
$r = new ReflectionFunction($c);

var_dump($r->getClosureThis()); // NULL, since the pseudo-variable $this is not available in a static context
var_dump($r->getClosureScopeClass()); // Corresponds to the self::class resolution inside a closure
var_dump($r->getClosureCalledClass()); // Corresponds to the static::class resolution inside a closure

?>

以上示例会输出:

string(1) "A"
string(1) "B"
NULL
object(ReflectionClass)#4 (1) {
  ["name"]=>
  string(1) "A"
}
object(ReflectionClass)#4 (1) {
  ["name"]=>
  string(1) "B"
}

参见

来源:PHP Documentation Group · 作者与贡献记录 · CC BY 3.0。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
PHP Documentation Group
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。