douhuanchi6586 2014-10-01 03:55
浏览 35
已采纳

为什么在调用反射方法时通过引用传递变量不起作用?

My function, prepare(), has the definition:

private function prepare(&$data, $conditions=null, $conditionsRequired=false)

When I test it, this

  /**
  * @covers /data/DB_Service::prepare
  * @uses /inc/config
  */
  public function testNoExceptionIsRaisedForValidPrepareWithConditionsAndConditionsRequiredArguments() {
    $method = new ReflectionMethod('DB_Service', 'prepare');
    $method->setAccessible(TRUE);

    $dbs = new DB_Service(new Config(), array('admin', 'etl'));
    $data = array('message' => '', 'sql' => array('full_query' => ""));
    $method->invoke($dbs, $data, array('conditionKey' => 'conditionValue'), TRUE);
  }

raises (and breaks my test)

ReflectionException: Invocation of method DB_Service::prepare() failed

However, this

  /**
  * @covers /data/DB_Service::prepare
  * @uses /inc/config
  */
  public function testNoExceptionIsRaisedForValidPrepareWithConditionsAndConditionsRequiredArguments() {
    $method = new ReflectionMethod('DB_Service', 'prepare');
    $method->setAccessible(TRUE);

    $dbs = new DB_Service(new Config(), array('admin', 'etl'));
    //$data is no longer declared - the array is directly in the call below
    $method->invoke($dbs, array('message' => '', 'sql' => array('full_query' => "")), array('conditionKey' => 'conditionValue'), TRUE);
  }

works perfectly and the test is successful.

Why does declaring the variable and then passing not work, but simply creating it in the method call does work? I think this has something to do with how invoke() works, but I can't seem to figure out what.

  • 写回答

1条回答 默认 最新

  • douchui1657 2014-10-01 04:10
    关注

    From the documentation for invoke:

    Note: If the function has arguments that need to be references, then they must be references in the passed argument list.

    So, your first example should work if you change it to:

    $method->invoke($dbs, &$data, array('conditionKey' => 'conditionValue'), TRUE);
    

    EDIT: To avoid deprecated call time pass-by-reference, you can use an array and invokeArgs:

    $method->invokeArgs($dbs, array(&$data, array('conditionKey' => 'conditionValue'), TRUE));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等