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

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

报告相同问题?

悬赏问题

  • ¥18 模拟电路问题解答有偿
  • ¥15 Matlab在app上输入带有矩阵形式的初始条件发生错误
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题