tags:

views:

193

answers:

5

How to call function of just created object without temporary variable?

Code

(new \Foo())->woof();

is not valid in php.

What is right?

+2  A: 

It can work if the object has singleton

Foo::getInstance()->woof();

BTW: it doesn't have to be even singleton but also static method which returns the instance

class Foo {
      public static function & getInstance()
      {
         return new self();
      }
}
Radek Suski
Gratuitous return by reference in the factory method.
Artefacto
That are good reasons for using a factory method, but doing so in order to avoid writing a few more characters when instantiating an object is not one of them.
Artefacto
+1  A: 
$obj = new Foo();
$obj->woof();

Sorry, no chaining allowed here.

Artefacto
A: 

This is, sadly, impossible.

Sjoerd
A: 

You need some form of a temporary variable. This work, but it's kinda hackish:

(${''} = new Foo())&&${''}->woof();

I like this solution because ${''} is the only way you can access this variable, so it's ok for temporary ones.

Maerlyn
That's not guaranteed to work, an object's conversion to bool can yield false.
Artefacto
@downvoters: I'd appreciate a comment.
Maerlyn
A: 

You can do it like this, but it's not very clean:

<?php

class Foo
{
  public function __construct()
  {
  }

  public function bar()
  {
    echo 'hello!';
  }
}

function Foo()
{
  return new Foo();
}

Foo()->bar();

You could also change it to something like

function newClass($className)
{
  return new $className();
}

newClass('Foo')->bar();

But the static method way is preferred.

raspi