作为引用从对象方法PHP返回的Change变量
我想覆盖作为引用返回的数组元素。我可以这样做:作为引用从对象方法PHP返回的Change变量,php,oop,pointers,object,reference,Php,Oop,Pointers,Object,Reference,我想覆盖作为引用返回的数组元素。我可以这样做: $tmp = $this->event_users_details; $tmp = &$tmp->firstValue("surcharge"); $tmp += $debt_amount; 我会在一行中这样做: $this->event_users_details->firstValue("surcharge") += $debt_amount; 但是我得不能在写上下文中使用方法返回值 其中$this->eve
$tmp = $this->event_users_details;
$tmp = &$tmp->firstValue("surcharge");
$tmp += $debt_amount;
我会在一行中这样做:
$this->event_users_details->firstValue("surcharge") += $debt_amount;
但是我得不能在写上下文中使用方法返回值
其中$this->event\u users\u details
是注入构造函数中的对象。
我的函数如下所示:
public function & firstValue(string $property) {
return $this->first()->{$property};
}
public function first() : EventUserDetails {
return reset($this->users);
}
而用户
是一个私有数组。
如果没有临时变量存储“附加费”值,则无法执行此操作
要从函数返回引用,请在函数声明中以及将返回值赋给变量时使用引用运算符(&R):
我用以下代码进行了检查:
类项目
{
公共$foo=0;
}
类容器
{
私有$arr=[];
公共函数构造()
{
$this->arr=[new Item()];
}
公共职能和第一价值($propNme)
{
返回$this->first()->{$propNme};
}
私有函数优先()
{
返回重置($this->arr);
}
}
$container=新容器();
var_dump($value=&$container->firstValue('foo');//0
$value+=1;
变量转储($container->firstValue('foo'));//1.