【问题标题】:PHP Carbon - variables bound to eachotherPHP Carbon - 相互绑定的变量
【发布时间】:2016-02-14 09:18:39
【问题描述】:

在 Laravel 5.2 控制器中使用 PHP Carbon 时,变量似乎相互绑定。因此,对其中一个的更改会影响其他的;

PHP函数:

$now = Carbon::now();

var_dump($now);

$from = $now;
$from->startOfYear();

var_dump('-----------------------------------');
var_dump($now, $from);

结果:

object(Carbon\Carbon)[225]
  public 'date' => string '2016-02-13 21:55:36.000000' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'UTC' (length=3)

string '-----------------------------------' (length=35)

object(Carbon\Carbon)[225]
  public 'date' => string '2016-01-01 00:00:00.000000' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'UTC' (length=3)

object(Carbon\Carbon)[225]
  public 'date' => string '2016-01-01 00:00:00.000000' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'UTC' (length=3)

$from 设置为年初也影响了$now,我不明白为什么,在互联网上搜索什么也没有。在函数中,我需要根据其他 Carbon 日期访问和操作 Carbon 日期,因此我不能对每个单独的 Carbon 日期实例使用 Carbon::now()

我该如何解决这个问题?是什么原因造成的?

更新

我无法回答为什么会发生这种情况,但我已经找到了一个临时解决方案,直到我能够深入了解它。从原始的碳日期创建一个新的碳日期,变成一个字符串。例如,$from = $new; 变为 $from = new Carbon($now->toDateTimeString());。您也可以照常访问方法;

$from = (new Carbon($now->toDateTimeString()))->startOfYear();.

【问题讨论】:

    标签: php laravel laravel-5.2 php-carbon


    【解决方案1】:

    当你分配一个对象时,你分配了它的内存地址,所以基本上你没有创建 2 个不同的碳对象,而是对同一个对象进行了 2 次引用。

    而不是这个 -

    $from = $now;

    使用 -

    $from = clone $now;

    您也可以使用 carbon copy() 方法,它与您在“黑客”中所做的基本相同 -

    $from = $now->copy();

    PHP Object Cloning

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-19
      • 2016-03-28
      • 2013-07-25
      • 1970-01-01
      • 2017-02-25
      • 1970-01-01
      • 2018-11-26
      • 1970-01-01
      相关资源
      最近更新 更多