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 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了
  • ¥15 微信小程序商城如何实现多商户收款 平台分润抽成
  • ¥15 HC32L176调试了一个通过TIMER5+DMA驱动WS2812B
  • ¥15 cocos的js代码调用wx.createUseInfoButton问题!
  • ¥15 关于自相关函数法和周期图法实现对随机信号的功率谱估计的matlab程序运行的问题,请各位专家解答!
  • ¥15 Python程序,深度学习,有偿私
  • ¥15 扫描枪扫条形码出现问题
  • ¥35 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?