В PHP можно ли инстанцировать объекта и назвать ли метод на той же строке?

Перечисления являются великолепным местом для затора полиморфного кода.

enum Rounding {
  ROUND_UP {
    public int round(double n) { ...; }
  },
  ROUND_DOWN {
    public int round(double n) { ...; }
  };

  public abstract int round(double n);
}

int foo(Rounding roundMethod) {
  return roundMethod.round(someCalculation());
}

int bar() {
  return foo(Rounding.ROUND_UP);
}
117
задан weotch 9 September 2009 в 22:38
поделиться

4 ответа

Как насчет:

$obj = new Obj(); $method_result = $obj->method(); // ?

: P

19
ответ дан 24 November 2019 в 02:06
поделиться

Нет, это невозможно.
Вам нужно назначить экземпляр переменной, прежде чем вы сможете вызвать какой-либо из ее методов.

Если вы действительно не хотите этого делать, вы можете использовать фабрику, как предлагает ropstah:

class ObjFactory{
  public static function newObj(){
      return new Obj();
  }
}
ObjFactory::newObj()->method();
16
ответ дан 24 November 2019 в 02:06
поделиться

Вы можете использовать статический фабричный метод для создания объекта:

ObjectFactory::NewObj()->method();
6
ответ дан 24 November 2019 в 02:06
поделиться

You cannot do what you are asking ; but you can "cheat", using the fact that, in PHP, you can have a function that has the same name as a class ; those names won't conflict.

So, if you declared a class like this :

class Test {
    public function __construct($param) {
        $this->_var = $param;
    }
    public function myMethod() {
        return $this->_var * 2;
    }
    protected $_var;
}

You can then declare a function that returns an instance of that class -- and has exactly the same name as the class :

function Test($param) {
    return new Test($param);
}

And now, it becomes possible to use a one-liner, like you asked -- only thing is you are calling the function, thus not using new :

$a = Test(10)->myMethod();
var_dump($a);

And it works : here, I'm getting :

int 20

as output.


And, better, you can put some phpdoc on your function :

/**
 * @return Test
 */
function Test($param) {
    return new Test($param);
}

This way, you'll even have hints in your IDE -- at least, with Eclipse PDT 2.x ; see the screeshot :



Edit 2010-11-30 : Just for information, a new RFC has been submitted, a few days ago, that proposes to add this feature to one of the future versions of PHP.

See : Request for Comments: Instance and method call/property access

So, maybe doing things like these will be possible in PHP 5.4 or another future version :

(new foo())->bar()
(new $foo())->bar
(new $bar->y)->x
(new foo)[0]
37
ответ дан 24 November 2019 в 02:06
поделиться
Другие вопросы по тегам:

Похожие вопросы: