【问题标题】:Object Copying and Evaluating $b = $a对象复制和评估 $b = $a
【发布时间】:2014-01-15 18:12:59
【问题描述】:

我的问题是输出中的 $b 与 $a 相同吗?我只是在使用 ($b = $a) 时传递了对 $a 的引用而不是复制对象吗?

$a = new DateTime('2014-01-15');
$i = new DateInterval('P1D');
print $a->format('Y-m-d') . PHP_EOL;          // 2014-01-15
$b = $a;
print $a->add($i)->format('Y-m-d') . PHP_EOL; // 2014-01-16
print $b->format('Y-m-d') . PHP_EOL;          // 2014-01-16

【问题讨论】:

    标签: php


    【解决方案1】:

    注意clone的用法:

    $a = new DateTime('2014-01-15');
    $i = new DateInterval('P1D');
    print $a->format('Y-m-d') . PHP_EOL;          // 2014-01-15
    $b = clone $a;                                // Here we clone the object
    print $a->add($i)->format('Y-m-d') . PHP_EOL; // 2014-01-16
    print $b->format('Y-m-d') . PHP_EOL;          // 2014-01-15
    

    来自文档的进一步解释:if your object holds a reference to another object which it uses and when you replicate the parent object you want to create a new instance of this other object so that the replica has its own separate copy. 听起来只是设置$a = $b 将具有相同的对象初始化,这意味着如果一个改变另一个。变量$b 成为一种符号链接,指向$a 中保存的初始化对象。

    【讨论】:

    猜你喜欢
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    • 2013-06-25
    • 1970-01-01
    相关资源
    最近更新 更多