In PHP, can you instantiate an object and call a method on the same line?

前端 未结 9 1817
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 14:01

What I would like to do is something like this:

$method_result = new Obj()->method();

Instead of having to do:

$obj = ne         


        
9条回答
  •  清酒与你
    2020-11-27 14:30

    No, this is not possible.
    You need to assign the instance to a variable before you can call any of it's methods.

    If you really wan't to do this you could use a factory as ropstah suggests:

    class ObjFactory{
      public static function newObj(){
          return new Obj();
      }
    }
    ObjFactory::newObj()->method();
    

提交回复
热议问题