clone:使用函数:php

时间:2015-12-31 09:45:52

标签: php

有人可以给我一个函数的diffrenet定义,可能还有一些例子吗?我真的不懂。它应该做什么?

<?php

    class Foo
    {
        var $that;

        function __clone()
        {
            $this->that = clone $this->that;
        }

    }

    $a = new Foo;
    $b = new Foo;
    $a->that = $b;
    $b->that = $a;

    $c = clone $a;
    echo 'What happened?';
    var_dump($c);
?>

我真的无法理解。

1 个答案:

答案 0 :(得分:0)

Private Sub TestSplits2Button_Click(sender As Object, e As EventArgs) Handles TestSplits2Button.Click
    Try
        Dim testString As String = "3XXX123456-C-AA123456TY-667"
        Dim vals() As String = testString.Split(Convert.ToChar("-"))
        Dim numberOfValues As Integer = vals.GetUpperBound(0)
        For Each testVal As String In vals
            Debug.Print(testVal)
        Next
    Catch ex As Exception
        MessageBox.Show(String.Concat("An error occurred: ", ex.Message))
    End Try
End Sub
  

对象(Foo)#2(1){[&#34;那&#34;] =&gt; object(Foo)#1(1){[&#34; that&#34;] =&gt;    RECURSION }}

class Foo // a class, it represents a real object normally
{
    var $that; //field called $that of class Foo

    function __clone() //In this SPECIAL case it overrides the normal clone function and what follows below is a custom body for this function
    {
        $this->that = clone $this->that; //set the field of this object (created from Foo) to a clone of that field. In other words force to point to a copy
    } //end of fucntion declaration

} //end of class declaration

$a = new Foo; //create object $a from class Foo
$b = new Foo; //create object $b from class Foo
$a->that = $b; //set $that property of object $a to point to $b
$b->that = $a; //set $that property of object $b to point to $a

$c = clone $a; // create a clone of $a and put it in variable $c CREATES AN ERROR!
echo 'What happened?'; //echo string litteral

var_dump($b); // I added this because:
/*
 *  *RECURSION* will occur (also if you dump $a)
 *   the output is:

您现在有一个循环引用

要更好地了解 */ var_dump($c); //print out object $c 我建议你阅读http://jacob-walker.com/blog/php-clone-and-shallow-vs-deep-copying.html