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();
精彩评论