php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #67409 Clone arguments
Submitted: 2014-06-10 10:12 UTC Modified: 2017-10-05 11:01 UTC
From: flip101 at gmail dot com Assigned:
Status: Wont fix Package: Class/Object related
PHP Version: Irrelevant OS:
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If this is not your bug, you can add a comment by following this link.
If this is your bug, but you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: flip101 at gmail dot com
New email:
PHP Version: OS:

 

 [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);


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2014-06-10 10:33 UTC] flip101 at gmail dot com
To clarify "The solution to the second use case" --> the situation right now without this feature.

in case __invoke() is implemented it is not called. Same behaviour as __construct(). See: http://codepad.viper-7.com/eBL3WY
 [2014-06-11 03:36 UTC] phpmpan at mpan dot pl
`clone` creates a clone of an object. That is: an object equivalent to the original one. If you want to create a method with a different contract then... create a method with a different contract.
 [2017-10-05 11:01 UTC] nikic@php.net
-Status: Open +Status: Wont fix
 [2017-10-05 11:01 UTC] nikic@php.net
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.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Apr 18 12:01:28 2024 UTC