php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #65718 __inClone() magic method to alter an object's inclusion in clones
Submitted: 2013-09-20 03:50 UTC Modified: 2013-09-20 04:10 UTC
From: metamarkers 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 you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: metamarkers at gmail dot com
New email:
PHP Version: OS:

 

 [2013-09-20 03:50 UTC] metamarkers at gmail dot com
Description:
------------
It would be nice if an object could determine whether or not it should be 
included in a clone, by returning a value that should be used in its stead, or an 
updated clone of itself, or anything of the like.

Test script:
---------------
class Foo { }

class Bar {
    public function __inClone ( $clone ) {
        return $clone instanceof Foo ? null : $this;
    } 
}

$foo = new Foo();
$foo->bar = new Bar();
$foo2 = clone $foo;
isset($foo2->bar); // false



Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2013-09-20 04:10 UTC] requinix@php.net
-Status: Open +Status: Wont fix
 [2013-09-20 04:10 UTC] requinix@php.net
That decision should be up to Foo, not up to Bar. If Foo is unaware that it no 
longer has a $bar member then that could introduce all sorts of unexpected and 
difficult to trace bugs.
Besides, PHP does not do deep copies during cloning anyways.

Implement Foo::__clone() such that it would normally clone all its members. Then 
you can
(a) Make it not clone its $bar and instead unset() it
(b) Implement a private Bar::__clone() so attempting to clone $bar raises a fatal 
"Call to private Bar::__clone from context 'Foo'"
(c) Implement a public Bar::__clone() and throw an Exception so attempting to 
clone $bar fails
Whichever way, Foo is responsible for knowing that Bar cannot be cloned and should 
adjust its own behavior accordingly.
 [2013-09-20 04:30 UTC] metamarkers at gmail dot com
Valid points. Thanks for reading.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Thu May 01 23:01:29 2025 UTC