2014-10-01 22 views
6

我的功能,編制(),有定義:爲什麼在調用反射方法時通過引用傳遞變量不起作用?

私有函數準備(& $數據,$條件= 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的調用::準備()失敗

然而,這

/** 
    * @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()的工作方式有關,但我似乎無法弄清楚。

回答

8

從文檔invoke

注:如果函數需要被引用的論點,那麼他們必須在傳遞的參數列表的引用。

所以,如果你將其更改爲你的第一個例子應該工作:

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

編輯:爲了避免過時的通話時間傳遞通過引用,你可以使用一個數組,invokeArgs

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

per [this SO post](http://stackoverflow.com/questions/8971261/php-5-4-call-time-pass-by-reference-easy-fix-available),這是棄用在PHP5中,它的使用是不鼓勵的。在方法定義中,我通過引用傳遞參數,所以在調用中再次這樣做不應該是正確的。 – 2014-10-01 04:16:09

+0

@MatthewHerbst你是對的,我的錯。 – wavemode 2014-10-01 04:21:13

+0

啊,那invokeArgs是偉大的。謝謝! – 2014-10-01 04:44:04

相關問題