|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2014-06-10 10:12 UTC] flip101 at gmail dot com
Description:
------------
It would be nice if the clone function could take arguments. Some scenario's where this would be useful:
1. The type of cloning, like deep-cloning (see given example)
2. Initialize with external values, similar to a constructor
The solution to the second use case would be to clone first and then set the property right on the clone. Which would need a public property, a setter or a hydration method (like reflection). Something that is sometimes not desired.
Test script:
---------------
<?php
class Bar { }
class Foo {
public function __construct() {
$this->bar = new Bar;
}
public function __clone($deep = false) {
if ($deep) {
$this->bar = clone $this->bar;
}
}
}
$a = new Foo;
$b = clone $a(true);
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Thu Nov 06 06:00:02 2025 UTC |
The `clone $a(true)` syntax is already in use: It will first call $a(true) and then clone the return value. As such we cannot introduce this functionality, at least in this form, without breaking existing code. You can easily achieve the desired behavior with a separate method: class Foo { public function deepClone() { $obj = clone $this; $obj->bar = clone $this->bar; return $obj; } } This does *not* require the "bar" property to be public, because visibility is bound to a certain scope, not to a certain object.