Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline PHP clone

Tags:

clone

php

inline

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?

like image 716
Thomas Ahle Avatar asked Mar 19 '14 16:03

Thomas Ahle


2 Answers

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'));
like image 90
Rocket Hazmat Avatar answered Oct 20 '22 23:10

Rocket Hazmat


class X {
    public function foo(){
        echo 'inline clone';
    }
}

$x = new X;

$y = clone $x and $y->foo(); // "inline clone"
like image 29
y o Avatar answered Oct 20 '22 23:10

y o