dongying3744 2016-08-30 10:49
浏览 12
已采纳

使用或不使用函数返回引用

Are there any actual difference between the two ways to get the value by reference?

Way 1

<?php
class foo {
    public $value = 42;

    public function &getValue() {
        return $this->value;
    }
}

$obj = new foo;
$myValue = &$obj->getValue();
// $myValue is a reference to $obj->value, which is 42.
$obj->value = 2;
echo $myValue;
// prints the new value of $obj->value, i.e. 2.
?>

Way 2

<?php
class foo {
    public $value = 42;
    public function getValue() {
        return $this->value;
    }
}

$obj = new foo;
$myValue = &$obj->value;
$obj->value = 2;
echo $myValue; 
?>

In both cases 2 is printed. So why does one need the getValue() function then? The first example is taken from the PHP Manual.

  • 写回答

1条回答 默认 最新

  • douyannuo7733 2016-08-30 10:59
    关注

    You need the first approach if class fields don't have a modifier 'public'. In this case you can't get a reference to the field outside the class. See example:

    <?php
    
    class foo
    {
        protected $value = 1;
    
        public function setValue($value)
        {
            $this->value = $value;
        }
    
        public function &getValue()
        {
            return $this->value;
        }
    }
    
    $obj = new foo;
    $myValue = &$obj->getValue();
    $obj->setValue(2);
    echo $myValue;
    ?> 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)