Inline PHP clone
Asked Answered
R

5

14

When trying to do this in PHP 5.2.9:

$foo = (clone $template)->bar();

PHP gives me a syntax error:

Parser error "';' expected after expression (Found token: ->)"

Am I doing something wrong? or is there simply no way to clone an object inline, such that I would have to split my statement into two lines?

Ratify answered 19/3, 2014 at 16:20 Comment(3)
I don't remember details, but older versions of PHP had trouble with some expressions related to object properties. Maybe this was one of them? Can you upgrade your version of PHP?Inconsistent
@Inconsistent Same problem with newer PHP versions but error is different.Skees
PHP 7 now supports this 3v4l.org/D5Vd9Dickson
F
11

Unfortunately, PHP does not allow that syntax (in any version). As an alternative to breaking it into two lines, you can do this:

$foo = call_user_func(array(clone $template, 'bar'));
Furred answered 19/3, 2014 at 16:27 Comment(3)
Too bad, I thought PHP had overcome those oddities by version 5. I'll consider the call_user_function version ;-)Ratify
I don't think there is any other way to one-line this. Or if there is, I don't know what it is :)Furred
Here's to hoping this gets added in PHP 7.Gershwin
U
3
class X {
    public function foo(){
        echo 'inline clone';
    }
}

$x = new X;

$y = clone $x and $y->foo(); // "inline clone"
Univalence answered 20/9, 2014 at 9:59 Comment(0)
H
0

This would be available only from PHP 5.4.0

Reading changelog:

Added class member access on instantiation (e.g. (new foo)->bar()) support.

Hypocaust answered 19/3, 2014 at 16:35 Comment(1)
Unfortunately, this syntax only works with new. It does not work with clone eval.in/123192 :(Furred
O
0

As a workaround you could create a function to clone a variable:

$clone = function ($value) {
    return clone $value;
};

$foo = $clone($template);
Ostler answered 30/8, 2017 at 14:56 Comment(0)
C
0
$newObject = (clone $objectToClone);

(Wont work in older verions of PHP, ok in 7.something+ though)

Cosignatory answered 6/10, 2023 at 11:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.