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

Add a Patch

Pull Requests

Add a Pull Request

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-2024 The PHP Group
All rights reserved.
Last updated: Wed Apr 24 08:01:29 2024 UTC