2017-01-15 14 views
0

参照として返された配列要素を上書きしたいと思います。オブジェクトメソッドからの参照として返された変数の変更PHP

$tmp = $this->event_users_details; 
$tmp = &$tmp->firstValue("surcharge"); 
$tmp += $debt_amount; 

は、私のような1行でそれを行うだろう:私はこのようにそれを行うことができます

$this->event_users_details->firstValue("surcharge") += $debt_amount; 

が、私は$this->event_users_detailsは、コンストラクタで注入したオブジェクトであるCan't use method return value in write context

を取得します。 My機能は、次のようになります。

public function & firstValue(string $property) { 
    return $this->first()->{$property}; 
} 

public function first() : EventUserDetails { 
    return reset($this->users); 
} 

usersは、プライベート配列です。

答えて

1

一時的な変数ストアの「追加料金」の値を入力しないとできません。

From documentation:

関数宣言と変数に戻り値を割り当てる両方の参照演算子&を使用し、関数からの参照を返すには:

<?php 
function &returns_reference() 
{ 
    return $someref; 
} 

$newref =& returns_reference(); 
?> 

私はこのコードでそれを確認:

class Item 
{ 
    public $foo = 0; 
} 

class Container 
{ 
    private $arr = []; 

    public function __construct() 
    { 
     $this->arr = [new Item()]; 
    } 

    public function &firstValue($propNme) 
    { 
     return $this->first()->{$propNme}; 
    } 

    private function first() 
    { 
     return reset($this->arr); 
    } 
} 

$container = new Container(); 
var_dump($value = &$container->firstValue('foo')); // 0 
$value += 1; 
var_dump($container->firstValue('foo')); // 1 
関連する問題