【问题标题】:Change variable returned as reference from object method PHP更改从对象方法 PHP 作为引用返回的变量
【发布时间】:2023-03-14 17:37:01
【问题描述】:

我想覆盖作为参考返回的数组元素。我可以这样做:

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

我会在一行中这样做:

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

但我得到Can't use method return value in write context

$this->event_users_details 是在构造函数中注入的对象。 我的功能如下:

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

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

users 是一个私有数组。

【问题讨论】:

    标签: php oop pointers object reference


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2018-05-28
      • 1970-01-01
      • 1970-01-01
      • 2015-12-18
      • 2015-12-21
      • 2023-01-04
      • 1970-01-01
      • 2021-01-30
      • 1970-01-01
      相关资源
      最近更新 更多