php-protobuf icon indicating copy to clipboard operation
php-protobuf copied to clipboard

how to deep copy a message object to another message object

Open crazier opened this issue 10 years ago • 10 comments

python have the CopyFrom method to copy all the values from another message of the same type as bar. but php assign a object to another object is not deep copy, and php-protobuf have the set{fieldname} function is also not deep copy.

So How to how to deep copy a message object to another message object

crazier avatar Aug 24 '16 15:08 crazier

php-protobuf doesn't provide an equivalent of Python's CopyFrom. If you have a simple object with scalar fields only, PHP's clone will do what you need:

$foo = new Foo();
$clonedFoo = clone $foo;

This is something that should be added.

hjagodzinski avatar Aug 24 '16 18:08 hjagodzinski

Or you can use this workaround:

$clonedFoo = new Foo();
$clonedFoo->parseFromString($foo->serializeToString());

serggp avatar Aug 24 '16 21:08 serggp

$foo = new Foo(); $clonedFoo = clone $foo; don't work. Because php protobuf class doesn't implement the __clone method

crazier avatar Aug 25 '16 03:08 crazier

A class doesn't need to implement a __clone method. You can find more details in official docs.

hjagodzinski avatar Aug 25 '16 06:08 hjagodzinski

Here is my test code: `
$target = new \Mmad\Myadinfo\MyAdTarget();

    $target1 = new  \Mmad\Myadinfo\MyAdTarget();
    $target->setMid(1234);
    $target1 = clone $target;

    $target->setMid(56789);
    var_dump($target1->printDebugString());`

var_dump($target1->printDebugString()) show 56789 not 1234

crazier avatar Aug 25 '16 07:08 crazier

You're right. I have just tested it myself. I was pretty sure it would work.

hjagodzinski avatar Aug 25 '16 07:08 hjagodzinski

@hjagodzinski but I need target1 keep 1234 not change to 56789. You mean you test and target1 and keep the 1234 ?

crazier avatar Aug 25 '16 08:08 crazier

I mean you're right, cloning doesn't work in case of ProtobufMessage class. The simplest option you have at your disposal is serialization and parsing.

hjagodzinski avatar Aug 25 '16 09:08 hjagodzinski

It is a bug that $target1 = clone $target; don't works

it is a temporary solution , in your proto class add this

public function getClone(){
    $clone = new static;
    $clone->parseFromString($this->serializeToString());
    return $clone;
}

sm2017 avatar Aug 26 '16 05:08 sm2017

A cloning an object with only scalar fields should work. I would like to investigate why it doesn't work in case of ProtobufMessage class. A support for cloning in general is up to class's author and lack of it should not be considered as a bug. It's optional feature, part of API, which you can provide but are not to obliged to do so.

hjagodzinski avatar Aug 26 '16 06:08 hjagodzinski