English 中文(简体)
1. 反向和用一种方法
原标题:Instantiate and call a method in one line
  • 时间:2010-09-21 12:24:07
  •  标签:
  • php
  • oop

是否有办法在一行中调用一个类别,将其方法称为一种? 我希望以下工作能够奏效,但确实如此:

(new User())->get_name();
最佳回答

这是不可能的。 然而,你可以形成一种静态的方法,恢复新的榜样。 类似:

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

User::create()->get_name();
问题回答

我知道这个问题是老的,但答复可能误导。

自第5条第4款以来,你可以直线使用方法:

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

rel=“nofollow noreferer”>http://docs.php.net/manual/en/migration54.new-features.php

Nope, sorry, 不幸的是,这在PHP中无所作为。 你们可以通过使用固定工厂方法或像这种方法那样做。

如果为你工作的话。 它把这一功能从非物体类别中划出。

User::get_name();




相关问题
Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

JSON with classes?

Is there a standardized way to store classes in JSON, and then converting them back into classes again from a string? For example, I might have an array of objects of type Questions. I d like to ...

Object-Oriented Perl constructor syntax and named parameters

I m a little confused about what is going on in Perl constructors. I found these two examples perldoc perlbot. package Foo; #In Perl, the constructor is just a subroutine called new. sub new { #I ...

Passing another class amongst instances

I was wondering what is the best practice re. passing (another class) amongst two instances of the same class (lets call this Primary ). So, essentially in the constructor for the first, i can ...

Where can I find object-oriented Perl tutorials? [closed]

A Google search yields a number of results - but which ones are the best? The Perl site appears to contain two - perlboot and perltoot. I m reading these now, but what else is out there? Note: I ve ...

热门标签