tags:

views:

221

answers:

2

Does anyone know if the following expression will be possible in the next version(s) of PHP?

(new A())->a();    // Causes a syntax error

I find very annoying that currently one must write 2 lines instead of 1:

$c = new A();
$c->a();
+4  A: 

The first version does not cause a parse error, it is perfectly valid. The second it is, indeed not possible, but you can easily overcome such a problem with some coding standards.

If every team member creates, for each defined class, a function with the same name as the class, and a signature similar to the signature of the class constructor, then you won't have the second problem. Example:

class Foo
{
    public function __construct($param)
    {}

    public function bar()
    {}
}

/**
 * @return Foo
 */
function Foo($param)
{
    return new Foo($param);
}

Foo()->bar();

Of course, you'll still have problems with library code.

Ionuț G. Stan
Right, the first one is non-issue. I must have confused it with something else. I'll edit the question. Thanks
Ivan Krechetov
I think you confused it with functionReturnsArray()[3], which is indeed not possible. There have been proposals, but they didn't get accepted. PHP internals don't like that shortcut.
Ionuț G. Stan
Exactly! That must be it!
Ivan Krechetov
Iount: do you have any links to the discussing regarding this? This is a feature I really miss :(
Jan Hancic
http://markmail.org/message/kk2hwn3gdjcw2yfh#query:related%3Akk2hwn3gdjcw2yfh+page:1+mid:5bv6mtd7zorni7gc+state:resultshttp://wiki.php.net/rfc/functionarraydereferencing
Ionuț G. Stan
Can anyone tell me if this is a common idiom in PHP? Do people often do this,that is define a global fn that returns the object?
Aaron
No, it's not a common idiom. I've seen it used by me and just one other person.
Ionuț G. Stan
"The first version does not cause a parse error, it is perfectly valid." Wish Stack Overflow had visible revisions so I could see what you're talking about here before it was edited. EDIT: Found them! Just need to click on the date. <3
mattalexx
+2  A: 

A new-expression can be used as a function argument. A function call can be used as the left-hand side of the member access operator. Therefore, you just need to define a single function:

function with($object) { return $object; }

with(new A()) -> a();

No additional efforts required on a per-class basis.

Victor Nicollet