php 如何深度复制 DateTime 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2579458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:59:49  来源:igfitidea点击:

How do I deep copy a DateTime object?

phpdatetime

提问by Billy ONeal

$date1 = $date2 = new DateTime();
$date2->add(new DateInterval('P3Y'));

Now $date1and $date2contain the same date -- three years from now. I'd like to create two separate datetimes, one which is parsed from a string and one with three years added to it. Currently I've hacked it up like this:

现在$date1$date2包含相同的日期 - 从现在起三年。我想创建两个单独的日期时间,一个是从字符串中解析出来的,另一个是添加了三年的时间。目前我已经破解了它:

$date2 =  new DateTime($date1->format(DateTime::ISO8601));

but that seems like a horrendous hack. Is there a "correct" way to deep copy a DateTime object?

但这似乎是一个可怕的黑客攻击。是否有一种“正确”的方式来深度复制 DateTime 对象?

回答by Amy B

$date1 = new DateTime();
$date2 = new DateTime();
$date2->add(new DateInterval('P3Y'));

Update:

更新:

If you want to copy rather than reference an existing DT object, use clone, not =.

如果要复制而不是引用现有 DT 对象,请使用clone,而不是=

$a = clone $b;

$a = clone $b;

回答by rjmunro

Clone the date with the cloneoperator:

使用克隆运算符克隆日期:

$date1 = new DateTime();
$date2 = clone $date1;
$date2->add(new DateInterval('P3Y'));

Clones are shallow by default, but deep enough for a DateTime. In your own objects, you can define the __clone()magic method to clone the properties (i.e. child objects) that make sense to be cloned when the parent object changes.

默认情况下,克隆是浅的,但对于 DateTime 来说足够深。在您自己的对象中,您可以定义__clone()魔术方法来克隆当父对象更改时克隆有意义的属性(即子对象)。

(I'm not sure why the documentation thinks a good example of needing to clone an object is GTK. Who uses GTK in PHP?)

(我不确定为什么文档认为需要克隆对象的一个​​很好的例子是 GTK。谁在 PHP 中使用 GTK?)

回答by Alexander Garden

PHP 5.5.0 introduced DateTimeImmutable. addand modifymethods of this class return new objects.

PHP 5.5.0 引入了DateTimeImmutable。此类的添加修改方法返回新对象。

$date1 = new DateTimeImmutable();
$date2 = $date1->add(new DateInterval('P3Y'));

回答by jave.web

TLDR:

域名注册地址:

$date1 = new DateTime();
$date2 = (clone $date1)->modify('+3 years');

(Shallow copy is enaugh - Deep copy-ing DateTime makes (currently) nosense)

(浅拷贝就够了 -深拷贝 DateTime 使得(当前)没有意义

Simple as that :)

就那么简单 :)

Explanation "php create datetime object from another datetime":

解释“php从另一个日期时间创建日期时间对象”:

  1. The clonekeyword makes regular shallowcopy - enaugh for this case (why => see below)
  2. Wraping it with ()evaluates the expression returning the newly created object by clone
  3. ->modify()is therefore called on and modifies the new object
  4. DateTime::modify(...)docs:

    Returns the DateTime object for method chaining or FALSE on failure.

  5. $date2now contains the newly created & modified clone/copy, while $date1remains unchanged

  1. clone关键字使常规拷贝- enaugh此情况下(为什么=>见下文)
  2. 用它包装它()评估返回新创建对象的表达式clone
  3. ->modify()因此被调用并修改新对象
  4. DateTime::modify(...)文档:

    返回用于方法链的 DateTime 对象,或者在失败时返回 FALSE。

  5. $date2现在包含新创建和修改的克隆/副本,而$date1保持不变

Why you don't need to deepcopy here:

为什么你不需要在这里拷贝:

Deep copy/clone is only necessary, when you need to copy targets of properties that are references, but this:

仅当您需要复制引用属性的目标时,才需要深度复制/克隆,但是:

class TestDateTime extends DateTime{
  public function test(){
   //*this* way also outputs private variables if any...
   var_dump( get_object_vars($this) );    
  }
}
$test = (new TestDateTime())->test();

outputs:

输出:

array(3) {
  ["date"]=>
  string(26) "2019-08-21 11:38:48.760390"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(3) "UTC"
}

so there are no references, just simple types => no need to deepcopy.

所以没有引用,只有简单的类型 => 不需要复制。

回答by Hossein Shahdoost

You should change your DateTimeto DateTimeImmutable

你应该改变你DateTimeDateTimeImmutable

// from date time
$date = \DateTimeImmutable::createFromMutable($mutableDate)

then you can call any method on the DateTimewithout worrying about it change

然后你可以调用任何方法DateTime而不必担心它会改变