PHP对象存储在变量中作为引用而不是值

时间:2016-11-10 22:22:47

标签: php laravel

我有一个使用Carbon存储当前日期的对象:

class Events {

  public $monthRange = 12;

  public $today;

  public function __construct() {
    $this->today = Carbon::now();
  }
}

我有一个扩展该类的类,我想在此设置一个$ d = $ this-的变量:

namespace Events;

use Carbon\Carbon;

class EventsData extends Events {

  public $monthsNames = [
    "1" => "January",
    "2" => "February",
    "3" => "March",
    "4" => "April",
    "5" => "May",
    "6" => "June",
    "7" => "July",
    "8" => "August",
    "9" => "September",
    "10" => "October",
    "11" => "November",
    "12" => "December"
  ];
  public function next_12_months() {
    $next_12_months = [];
    $d = $this->today;

    array_push($next_12_months, $d->month);
    for ( $i = 0; $i <= ($this->monthRange - 1); $i++ ) {
      $d = $d->addMonths(1);
      if ( $this->today != $d) {
        array_push($next_12_months, $d->year);
      }
      var_dump($$this->today); //is being modified along with $d
      var_dump($d);
      $next_month = $d->month;
      array_push($next_12_months, $next_month);
    }

    return $next_12_months;
  }
}

问题在于,当我修改$ d时,如$ d-&gt; addMonths(1),似乎$ this-&gt;今天也会被修改。

如何防止这种情况发生?

1 个答案:

答案 0 :(得分:1)

克隆对象

$d = clone $this->today;

有关克隆here的更多信息。