how to deep copy a message object to another message object
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
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.
Or you can use this workaround:
$clonedFoo = new Foo();
$clonedFoo->parseFromString($foo->serializeToString());
$foo = new Foo(); $clonedFoo = clone $foo;
don't work.
Because php protobuf class doesn't implement the __clone method
A class doesn't need to implement a __clone method. You can find more details in official docs.
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
You're right. I have just tested it myself. I was pretty sure it would work.
@hjagodzinski but I need target1 keep 1234 not change to 56789. You mean you test and target1 and keep the 1234 ?
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.
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;
}
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.