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

前端 未结 9 1734
没有蜡笔的小新
没有蜡笔的小新 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();
    
    0 讨论(0)
  • 2020-11-27 14:30

    I, too, was looking for a one-liner to accomplish this as part of a single expression for converting dates from one format to another. I like doing this in a single line of code because it is a single logical operation. So, this is a little cryptic, but it lets you instantiate and use a date object within a single line:

    $newDateString = ($d = new DateTime('2011-08-30') ? $d->format('F d, Y') : '');
    

    Another way to one-line the conversion of date strings from one format to another is to use a helper function to manage the OO parts of the code:

    function convertDate($oldDateString,$newDateFormatString) {
        $d = new DateTime($oldDateString);
        return $d->format($newDateFormatString);
    }
    
    $myNewDate = convertDate($myOldDate,'F d, Y');
    

    I think the object oriented approach is cool and necessary, but it can sometimes be tedious, requiring too many steps to accomplish simple operations.

    0 讨论(0)
  • 2020-11-27 14:33

    Simply we can do this

    $method_result = (new Obj())->method();
    
    0 讨论(0)
提交回复
热议问题