tags:

views:

235

answers:

4

What I would like to do is something like this:

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

Instead of having to do:

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

The result doesn't actually matter to me in my specific case. But, is there a way to do this?

+8  A: 

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();
  }
}
objFacotry::newObj()->method();
Pim Jager
Pim's answer is correct. Alternatively you could use static functions if you do not wish to create an instance of the object
Mark
What's a objFacotry? ;)
Ropstah
+3  A: 

You could use a static factory method to produce the object:

ObjectFactory::NewObj()->method();
Ropstah
+3  A: 

How about:

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

:P

Jeff
Great answer :P Made me laugh.
Chris Mazzola
+7  A: 

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 :

Pascal MARTIN
nice! didn’t know that
knittl
Me neither, thanks.
Ropstah
Wow, very nice! I didn't know that.
Pim Jager
Thanks ;-) I don't recall where I saw this trick first... But I thought it was nice/fun, and have used it a couple of times since ^^
Pascal MARTIN