tags:

views:

53

answers:

3

Is there a way to instantiate a class and call one of its methods in one line? I hoped the following would work but it doesn't:

(new User())->get_name();
+2  A: 

Nope, sorry, this unfortunately doesn't work in PHP. You could work around it by using a static factory method or something like that though.

Raoul Duke
+5  A: 

This is not possible. You could, however, create a static method returning a new instance. Something like:

class User {
    public static function create() {
        return new self();
    }
}

User::create()->get_name();
bouke
That would work for me. Thanks!
Emanuil
+1  A: 

Try if this works for you. It calls the function from the class not an object.

User::get_name();
erikb