开发者

Instantiate and call a method in one line

开发者 https://www.devze.com 2023-01-17 12:04 出处:网络
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:

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();


I know this question is old but the replies can be misleading.

Since version 5.4 you can instantiate and call methods inline:

(new Foo())->bar();

http://docs.php.net/manual/en/migration54.new-features.php


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();


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.


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

User::get_name();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号