gpt4 book ai didi

PHP Carbon - 相互绑定(bind)的变量

转载 作者:行者123 更新时间:2023-12-02 06:31:25 26 4
gpt4 key购买 nike

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

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::now()对于碳日期的每个单独实例。

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

更新

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

最佳答案

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

而不是这个 -
$from = $now;
采用 -
$from = clone $now;
您也可以使用碳 copy()方法基本上与您在“hack”中所做的相同 -
$from = $now->copy();

PHP Object Cloning

关于PHP Carbon - 相互绑定(bind)的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35385876/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com