Re: Pass source object to clone like __clone($origThis)
| From: | Michael Voříšek - ČVUT FEL | Date: | Thu, 03 Sep 2020 16:36:46 +0000 |
| Subject: | Re: Pass source object to clone like __clone($origThis) | ||
| References: | 1 2 3 4 5 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-111832@lists.php.net to get a copy of this message | ||
The goal is to be able to access the original object and it's id/hash.
Usecases:
- something is associated with the object using the object id/hash and
it needs to be cloned as well
we need the original object to obtain it's id/hash for spl_object_id and
spl_object_hash methods
- bounded Closures ar associated with the original object and they needs
to be rebound to the cloned object
example:
public function __clone(self $origThis)
{
if ((new \ReflectionFunction($this->fx))->getClosureThis() ===
$origThis) {
$this->fx = \Closure::bind($this->fx, $this);} } Modification of php is simple: https://github.com/php/php-src/pull/6063/files#diff-beea8c5a8ceb318220b34b73e4ecfc98R252 we simply pass the old object as 1 parameter. I belive, passing old object have positives and no performance nor compatibility impact. All other current solutions require an extra property and a lot of code, as assigning in constructor is not enough (due serialization etc.), or it is even impossible, if object was created using reflection without constructor. With kind regards / Mit freundlichen Grüßen / S přátelským pozdravem, Michael Voříšek On 3 Sep 2020 18:00, Sara Golemon wrote:
On Thu, Sep 3, 2020 at 10:40 AM David Rodrigues <david.proweb@gmail.com> wrote:Now I rethinked about what I said. Really, maybe clone is not the best option. So maybe we can just use a method that will clone and will have access to both informations. But I don't know if it solves the original message. public function getUserCopy() { $userCopy = clone $this; $this->copies[] = $userCopy; return $userCopy; }If your goal is to track copies, then a static makes much more sense. class AllKnowing { private static $copies = []; public function __construct(...) { self::$copies[] = $this; .... } public function __clone() { self::$copies[] = $this; } } -Sara