1

Possible Duplicate:
PHP: How to chain method on a newly created object?

I can create an instance and call it's method via:

$newObj = new ClassName();
$newObj -> someMethod();

But is there any way I can do it in a shorter notation, an anonymous instance? I tried this:

(new ClassName())->someMethod();

But it doesn't seem to work as expected.

Additional Info: The method I want to call is public but not static.

Community
  • 1
  • 1
DanRedux
  • 9,119
  • 6
  • 23
  • 41

3 Answers3

5

PHP 5.4 supports it.

If you can't update you can workaround like this:

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

yourclass()->method();

Don't forget that your constructor must return $this;

dynamic
  • 46,985
  • 55
  • 154
  • 231
3

Not that i know of.

But! - You could implement a Singleton Pattern and then call:

ClassName::getInstance()->someMethod();

Or, to cut it short ;)

ClassName::gI()->someMethod();

If someMethod does not refer to $this, you could also simply call it as a static function, though it wasn't defined as one:

ClassName::someMethod();
Phil Rykoff
  • 11,999
  • 3
  • 39
  • 63
  • As far as I know, you can only have one singleton. I'm afraid this is a regular object, some will be anonymous, but some will be stored in containers or arrays or even other objects. Unless I can make getInstance return a new instance of the object.. I'll try it. – DanRedux Mar 13 '12 at 19:21
  • It worked perfectly! My constructor has optional params, so I had to include those in my getInstance() class when it made a new instance and returned it, but it definitely worked. Thanks. My chains look a lot cleaner now. I'll accept as soon as it lets me. – DanRedux Mar 13 '12 at 19:25
0

If the method is static and doesn't rely on any class variables (maybe you've put it in a class just for organisation purposes), you can simply call it staticly as phil is demonstrating with getInstance:

ClassName::someMethod()
Endophage
  • 21,038
  • 13
  • 59
  • 90