du970294 2016-09-15 13:23
浏览 34
已采纳

通过引用传递与通过值传递

<?php
function sum($y) {
$y = $y + 5; 
}

$x = 5;
sum($x);
echo $x;
?>

So I have this code. The questions are: What does it output? The answer: 5. How do I make it to output 10? The answer: sum(&$x).

The problem is that I don't understand why the answer to the first question is 5. When you make sum($x), shouldn't it replace the function with $x, so $x= 5+5=10? Why the answer is 5? I really don't understand. Someone explaind me something related to pointers and the adress, but I didn't understand. I never understood the concept of pointers, and I googled it and apparently there are no pointers in php, so I'm super confused. My friend said that a variable is formed of a value, and the memory adress of that value. Can someone explain me like I'm 5 years old why the answer is 5 and not 10? Please

  • 写回答

3条回答 默认 最新

  • doulangbizhan5160 2016-09-15 13:33
    关注

    Let's pretend $x is a piece of paper with 5 written on it.

    function sum($y) {
      $y = $y + 5; 
    }
    

    Here $y is the value of what you have written. You add 5 to such value in your mind, but the note is left untouched.

    function sum(&$y) {
      $y = $y + 5; 
    }
    

    With the reference operator (&$y), you pass the very paper to the function, and it overwrites what's written on it.


    For primitive values like numbers, I wouldn't bother and always return the value you want:

    function valuePlusFive($x) {
      return $x + 5;
    }
    
    $x = 5;
    $x = valuePlusFive($x);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度