Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instancing an object and calling a method in one line?

Tags:

oop

php

php 5.3

Is there a way to do this (viable in java for example)

(new MyClass())->myMethod();

i am receving: Parse error: syntax error, unexpected T_OBJECT_OPERATOR in D.. on line 7

Add

I really need that RFC to be implemented in the next PHP version!

http://wiki.php.net/rfc/instance-method-call

Is there a way we can subscribe to it so it can get more attention?

like image 832
dynamic Avatar asked Mar 10 '11 23:03

dynamic


1 Answers

No, its not possible. There is a RFC for that

http://wiki.php.net/rfc/instance-method-call

But no one knows, when this will come to the userland.

Jacob mentioned the static method. There are other more or less useful methods to achieve the same

function instanciate($className, $arg1 = null) {
    $args = func_get_args();
    array_shift($args);
    $c = new ReflectionClass($className);
    return $c->newInstanceArgs($c);
}
instanciate('Classname', 1, 2, 3)->doSomething();

However, I prefer the temporary variable (like in the question).

Update: I can swear there where an example for the temporary variable stuff in the question in the past. However, I meant this

$x = new Class;
$x->method();

where $x is the temporary variable.

like image 188
KingCrunch Avatar answered Sep 28 '22 03:09

KingCrunch