doudou3935 2015-04-17 18:38
浏览 44
已采纳

PHP变量值更改

This problem is simpler to explain with the code. Note that functions are located in a different file and are being included on the page.

$announcements = $dbc->query($q)->results(); //Returns array of objects
$announcements = prepareMessage($announcements); //Adds html tags to values
$latest = $announcements[0]; //Assign first index to variable
$announcements = truncate($announcements); //Truncate announcement text

function prepareMessage($message) {
    foreach($message as $values => $key) {
        $key->title = '<h2>'.$key->title.'</h2>';
        $key->name = '<p>'.$key->name.'</p>';
        $key->date = '<small>'.humanDate($key->date).'</small>';
    }

    return $message;
}

function truncate($message) {
    foreach($message as $values => $key) {
        $key->announcement = substr($key->announcement, 0, 50) . '...</p>';
    }

    return $message;
}

The value of the $latest variable changes after I run this line of code

$announcements = truncate($announcements);

$latest value before that line is ran

[announcement] =>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua.

$latest value after that line is ran

[announcement] =>
Lorem ipsum dolor sit amet, consectetur adipisc...

So my question is, why is the value of $latest changing?

  • 写回答

3条回答 默认 最新

  • dongrong1856 2015-04-17 18:55
    关注

    Because $latest is a reference to $announcements[0], not the actual value of $announcements[0]. Instead, use a clone. In PHP5, object assignments are always by reference.

    $latest = clone $announcements[0]; //Clone first object in array
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?