(PHP 5 >= 5.4.0, PHP 7, PHP 8)
ReflectionFunctionAbstract::getClosureScopeClass — 傳回閉包內部範圍對應的類別
以 ReflectionClass 的形式傳回與 Closure 內部範圍對應的類別。
此函式沒有參數。
返回一個對應到使用此 Closure 的類別範圍的 ReflectionClass。如果函式不是閉包,或者它具有全域範圍,則會返回 null
。
範例 #1 展示 ReflectionFunctionAbstract::getClosureCalledClass()、ReflectionFunctionAbstract::getClosureScopeClass() 和 ReflectionFunctionAbstract::getClosureThis() 在物件上下文中的閉包之間的差異
<?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,因為非靜態閉包會採用物件上下文
var_dump($r->getClosureScopeClass()); // 對應於閉包內 self::class 的解析結果
var_dump($r->getClosureCalledClass()); // 對應於閉包內 static::class 的解析結果
?>
以上範例將輸出
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 展示 ReflectionFunctionAbstract::getClosureCalledClass()、ReflectionFunctionAbstract::getClosureScopeClass() 和 ReflectionFunctionAbstract::getClosureThis() 在沒有物件上下文靜態閉包之間的差異
<?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,因為在靜態環境下無法使用偽變數 $this
var_dump($r->getClosureScopeClass()); // 對應閉包內 self::class 的解析結果
var_dump($r->getClosureCalledClass()); // 對應閉包內 static::class 的解析結果
?>
以上範例將輸出
string(1) "A" string(1) "B" NULL object(ReflectionClass)#4 (1) { ["name"]=> string(1) "A" } object(ReflectionClass)#4 (1) { ["name"]=> string(1) "B" }