【问题标题】:Why does passing a variable by reference not work when invoking a reflective method?为什么在调用反射方法时通过引用传递变量不起作用?
【发布时间】:2014-11-25 20:25:09
【问题描述】:

我的函数prepare()有如下定义:

私有函数prepare(&$data, $conditions=null, $conditionsRequired=false)

当我测试它时,这个

  /**
  * @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);
  }

提高(并打破了我的测试)

ReflectionException:方法 DB_Service::prepare() 的调用失败

但是,这个

  /**
  * @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);
  }

完美运行,测试成功。

为什么声明变量然后传递不起作用,而只是在方法调用中创建它就起作用了?我认为这与 invoke() 的工作原理有关,但我似乎无法弄清楚是什么。

【问题讨论】:

    标签: php reflection phpunit pass-by-reference


    【解决方案1】:

    来自invoke 的文档:

    注意:如果函数有参数需要引用,那么它们必须是传递参数列表中的引用。

    因此,如果您将第一个示例更改为:

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

    编辑:为避免不推荐使用的调用时间传递引用,您可以使用数组和invokeArgs

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

    【讨论】:

    • 根据this SO post,这在 PHP5 中已被弃用,不鼓励使用。在方法定义中我通过引用传递参数,所以在调用中再次这样做不应该是正确的。
    • @MatthewHerbst 你完全正确,我的错。
    • 啊,invokeArgs 很棒。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 2013-08-22
    • 2017-01-20
    • 2018-06-20
    • 1970-01-01
    • 2015-12-29
    • 2011-12-18
    相关资源
    最近更新 更多