php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #70414 FR: support to clone() keyword
Submitted: 2015-09-02 20:57 UTC Modified: 2016-03-27 16:23 UTC
From: david dot proweb at gmail dot com Assigned:
Status: Wont fix Package: Scripting Engine problem
PHP Version: Next Minor Version OS:
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: david dot proweb at gmail dot com
New email:
PHP Version: OS:

 

 [2015-09-02 20:57 UTC] david dot proweb at gmail dot com
Description:
------------
It should works exactly like the `clone`, but with some features.

    // Usage.
    clone($user)->find(1);

    // Currently (too verbose):
    $userClone = clone $user;
    $userClone = $userClone->find(1);

    // __clone() reinforcement: callback that can 
    // - get/set private/protected attributes or 
    // call private/protected methods.
    clone($user, function ($baseObject) use ($externalData) {
        $this->privateAttribute = $baseObject->privateAttribute + $externalData;
    });

Signature (pseudo-code):

    function clone ($object, callable $callback = null) {
        assert(is_object($object));
     
        if (!$callback) return clone $object;

        // __clone() is called here.
        $clone = clone $object; 

        // Pass $clone as $this, and $object as first parameter.
        // Before call(), __clone() is called.
        $callback->call($clone, $object);

        return $clone;
    }



Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2015-09-02 21:24 UTC] stas@php.net
-Package: PHP Language Specification +Package: Scripting Engine problem
 [2015-09-02 21:37 UTC] requinix@php.net
Calling code should not even be aware of the existence of private or protected variables, let alone need to modify them after cloning.

Like the other request, your use case is easily solved with a userland function.
 [2016-03-27 16:23 UTC] nikic@php.net
-Status: Open +Status: Wont fix
 [2016-03-27 16:23 UTC] nikic@php.net
Closing as Won't Fix, because:

a) In PHP 7 you can write (clone $user)->find(1), covering your first point.
b) As requinix points out, the calling code has no business touching private properties of the object. If you want to do something, you are free to use one of the usual hacks for avoiding visibility checks (e.g. reflection or closure rebinding).
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Apr 18 11:01:28 2024 UTC