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


PHP object is being stored in variable as a reference rather than value

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

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

我有一个类,扩展了这个类,我想设置一个变量$d = $this-today,如:

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->addMonths(1),似乎$this->今天也得到修改。

如何防止这种情况发生?

克隆对象

$d = clone $this->today;

关于克隆的更多信息请点击这里