douyong1885 2015-08-09 23:36
浏览 55
已采纳

如何从私有函数中获取PHP变量

How can I get the variable $components out of this class and private function:

class WPCF7_Mail {
    private function compose() {

        return $components;
    }
}

This is my best attempt:

class test extends WPCF7_Mail {
    function compose( $send = true ) {
        global $components;
    }
}

new test();
global $components;
echo $components;

But I keep getting:

Fatal error: Call to private WPCF7_Mail::__construct() from invalid context

Edit: I cannot modify the class WPCF7_Mail. So I cannot make the function compose public.

  • 写回答

1条回答 默认 最新

  • duancong6937 2015-08-10 01:40
    关注

    You can get the private property or call a private function by using ReflectionClass::newInstanceWithoutConstructor() and Closure::bind().

    Make sure that WPCF7_Mail is in the same Namespace, otherwise you'll need to provide the full namespace name (e.g '\Full\Namespace\WPCF7_Mail').

    If you don't have a private/protected constructor with required parameters, you can simply use the class and Closure::bind().

    $class = (new ReflectionClass('WPCF7_Mail'))->newInstanceWithoutConstructor();
    $getter = function ($a) {
        return $a->components;
    };
    $getter = Closure::bind($getter, null, $class);
    var_dump($getter($class));
    

    If you need to call the function, you can do it like this:

     $class = (new ReflectionClass('WPCF7_Mail'))->newInstanceWithoutConstructor();
     $getter = function ($a) {
        return $a->compose();
     };
     $getter = Closure::bind($getter, null, $class);
     var_dump($getter($class));
    

    Note that this will work starting with php version 5.4

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?