php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #55833 Dereferencing clone operation
Submitted: 2011-10-02 22:39 UTC Modified: 2014-10-12 14:59 UTC
Votes:5
Avg. Score:3.8 ± 0.7
Reproduced:5 of 5 (100.0%)
Same Version:2 (40.0%)
Same OS:1 (20.0%)
From: hakon dot trandal at gmail dot com Assigned: nikic (profile)
Status: Closed Package: Scripting Engine problem
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: hakon dot trandal at gmail dot com
New email:
PHP Version: OS:

 

 [2011-10-02 22:39 UTC] hakon dot trandal at gmail dot com
Description:
------------
This suggestion is similar to "Instance and method call/property access"[1] and array dereferencing[2].

Currently, if you want to perform an operation on a cloned object you have to assign the result to a temporary variable:
$clonedObject = clone $otherObject;
$result = $clonedObject->doSomething();

It should be possible to call "doSomething()" directly after the clone operation:
$result = (clone $otherObject)->doSomething();

This would be especially useful in fluent interfaces:
$criteria = ArticleQuery::create()
    ->filterByIsPublished(true)
    ->orderByPublishFrom(Criteria::DESC)
    ->joinWith('Article.Author')
    ->limit(10);
$news = (clone $criteria)
    ->filterByType('news')
    ->find();
$articles = (clone $critera)
    ->filterByType('article')
    ->find();

[1] https://wiki.php.net/rfc/instance-method-call
[2] http://schlueters.de/blog/archives/138-Features-in-PHP-trunk-Array-dereferencing.html

This suggestion originated on stack overflow:
http://stackoverflow.com/questions/7629196/why-must-we-assign-a-clone-to-a-new-variable/

Test script:
---------------
class MyClass {
    public $myVar = "original";
    public function doSomething() {
        $this->myVar = "did something";
        return $this;
    }
}

$a = new MyClass();
echo (clone $a)->doSomething()->myVar;
echo $a->myVar;


Expected result:
----------------
did something
original


Actual result:
--------------
Parse error: syntax error, unexpected T_OBJECT_OPERATOR

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2014-10-12 14:59 UTC] nikic@php.net
-Status: Open +Status: Closed -Assigned To: +Assigned To: nikic
 [2014-10-12 14:59 UTC] nikic@php.net
Supported in PHP 7.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Thu Jul 03 00:01:35 2025 UTC