Search code examples
phpoopclone

How to write my own clone function


Every object-oriented language (or language which supports OOP), be it C++, Java, Python, PHP has a clone function of its own, which can return a deep or shallow copy of an object. Can anybody tell me how to create my own clone function from scratch, for both deep and shallow copy? Obviously I can't use any language-construct like serialize, not to mention clone itself! An example in PHP would be great, though any other language is fine as well, I need to know how to do it, that's all.


Solution

  • Part 1

    /* memcpy example */
    #include <stdio.h>
    #include <string.h>
    
    struct {
      char name[40];
      int age;
    } person, person_copy;
    
    int main ()
    {
      char myname[] = "Pierre de Fermat";
    
      /* using memcpy to copy string: */
      memcpy ( person.name, myname, strlen(myname)+1 );
      person.age = 46;
    
      /* using memcpy to copy structure: */
      memcpy ( &person_copy, &person, sizeof(person) );
    
      printf ("person_copy: %s, %d \n", person_copy.name, person_copy.age );
    
      return 0;
    }
    

    taken from http://www.cplusplus.com/reference/clibrary/cstring/memcpy/

    Part 2

    1

    I'm assuming you need to copy all child elements of complicated objects(as in copying imaginary object A in figure 1,the code I've linked above can be used if you need only to copy the black color object but keeping others as references , the below pseudo code is for if you want to copy its all child items as well) Above figures shows how the reality and how we think of an object

    function MyCloneRecursive(object A) : object
    {
        pointer Cpy;
        allocate memory to Cpy;
        memcpy(&Cpy,&A,sizeof(A))
        //now copy all its child elements
        //assuming there is a way to do a foreach that
        //for object A there are A.B,A.C and inside A.B there is D
        //and childname={"B","C"} and inside of B childname={"D"}
        for each childname in object A 
        {
            eval("Cpy." + childname + "=MyCloneRecursive(A." + childname + ")");
        }
    }
    
    //note this is really bad programming 
    //clone function is better written in the runtime
    //(or its a part of the intepreter not a includable code)