略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: ReflectionMethod::getClosure

2024-04-28

ReflectionMethod::getClosure

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

ReflectionMethod::getClosure返回一个动态建立的方法调用接口,译者注:可以使用这个返回值直接调用非公开方法。

说明

public ReflectionMethod::getClosure(object $object): Closure

警告

本函数还未编写文档,仅有参数列表。

参数

object

不可以使用静态方法,需要其他类型的方法

返回值

返回 Closure 如果产生任何错误返回 null

add a noteadd a note

User Contributed Notes 2 notes

up
14
Denis Doronin
9 years ago
You can call private methods with getClosure():

<?php

function call_private_method($object, $method, $args = array()) {
   
$reflection = new ReflectionClass(get_class($object));
   
$closure = $reflection->getMethod($method)->getClosure($object);
    return
call_user_func_array($closure, $args);
}

class
Example {

    private
$x = 1, $y = 10;

    private function
sum() {
        print
$this->x + $this->y;
    }

}

call_private_method(new Example(), 'sum');

?>

Output is 11.
up
-1
okto
5 years ago
Use method from another class context.

<?php

class A {
    private
$var = 'class A';

    public function
getVar() {
        return
$this->var;
    }

    public function
getCl() {
        return function () {
           
$this->getVar();
        };
    }
}

class
B {
    private
$var = 'class B';
}

$a = new A();
$b = new B();

print
$a->getVar() . PHP_EOL;

$reflection = new ReflectionClass(get_class($a));
$closure    = $reflection->getMethod('getVar')->getClosure($a);
$get_var_b  = $closure->bindTo($b, $b);

print
$get_var_b() . PHP_EOL;

// Output:
// class A
// class B

官方地址:https://www.php.net/manual/en/reflectionmethod.getclosure.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3