📜  如何在PHP复制 DateTime 对象?

📅  最后修改于: 2022-05-13 01:54:11.699000             🧑  作者: Mango

如何在PHP复制 DateTime 对象?

给定一个 DateTime 对象,任务是创建该对象的副本。要创建 DateTime 对象的副本,我们使用 clone 关键字,如下所述:
DateTime 对象的副本是通过使用 clone 关键字创建的(如果可能,它会调用对象的 __clone() 方法)。不能直接调用对象的 __clone() 方法。当对象被克隆时, PHP将执行对象所有属性的浅拷贝。任何引用其他变量的属性都将保持引用。

句法:

$DateTime_copy_object_name = clone $DateTime_object_to_be_copied

下面的例子说明了在PHP克隆 DateTime 对象:

示例 1:

PHP
format('Y-m-d H:i:s');
echo "Original object: $result\n";
 
$result = $copy->format('Y-m-d H:i:s');
echo "Cloned object: $result\n\n";
 
 
// Changing original object ($obj) value
// to verify other($copy) is clone or not
 
// This statement will add 3 Days
$obj->add(new DateInterval('P3D'));
 
// Printing values
echo "Printing values after change\n";
 
$result = $obj->format('Y-m-d H:i:s');
echo "Original object: $result\n";
 
 
$result = $copy->format('Y-m-d H:i:s');
echo "Cloned object: $result\n";
?>


PHP
format('Y-m-d H:i:s');
echo "Original object: $result\n";
 
$result = $ref_obj->format('Y-m-d H:i:s');
echo "Reference object: $result\n";
 
$result = $copy->format('Y-m-d H:i:s');
echo "Cloned object: $result\n\n";
 
 
// Changing original object ($obj) value
// to verify other($copy) is clone or not
 
// This statement will add 3 Months
$obj->add(new DateInterval('P3M'));
 
// Printing values
echo "Printing values after change\n";
 
$result = $obj->format('Y-m-d H:i:s');
echo "Original object: $result\n";
 
$result = $ref_obj->format('Y-m-d H:i:s');
echo "Reference object: $result\n";
 
$result = $copy->format('Y-m-d H:i:s');
echo "Cloned object: $result\n";
?>


输出:



Printing initial values
Original object: 2020-04-14 17:14:18
Cloned object: 2020-04-14 17:14:18

Printing values after change
Original object: 2020-04-17 17:14:18
Cloned object: 2020-04-14 17:14:18

示例 2:下面的程序将 clone 与赋值 (=)运算符区分开来。

PHP

format('Y-m-d H:i:s');
echo "Original object: $result\n";
 
$result = $ref_obj->format('Y-m-d H:i:s');
echo "Reference object: $result\n";
 
$result = $copy->format('Y-m-d H:i:s');
echo "Cloned object: $result\n\n";
 
 
// Changing original object ($obj) value
// to verify other($copy) is clone or not
 
// This statement will add 3 Months
$obj->add(new DateInterval('P3M'));
 
// Printing values
echo "Printing values after change\n";
 
$result = $obj->format('Y-m-d H:i:s');
echo "Original object: $result\n";
 
$result = $ref_obj->format('Y-m-d H:i:s');
echo "Reference object: $result\n";
 
$result = $copy->format('Y-m-d H:i:s');
echo "Cloned object: $result\n";
?>

输出:

Printing initial values
Original object: 2020-04-14 17:14:49
Reference object: 2020-04-14 17:14:49
Cloned object: 2020-04-14 17:14:49

Printing values after change
Original object: 2020-07-14 17:14:49
Reference object: 2020-07-14 17:14:49
Cloned object: 2020-04-14 17:14:49

因此,要复制我们使用 clone 的对象,不要使用 (=)运算符,因为它会创建引用。