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 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教