The SpiteShow
PHP Object stuff

marco:

Can PHP do this?

(new Whatever())->function();

It gives me a parse error and makes me do this instead:

$w = new Whatever(); $w->function();

But you can do this perfectly well:

$w->function()->otherFunction();

One hack is to define a function with the same name as the class that returns an instance:

function Whatever() { return new Whatever(); }
/* ... */
Whatever()->function()->otherFunction();

But that’s a hack.

I do this with some of my stuff:


class Test
{
	protected function __construct() {
		// some config stuff...set some stuff
	}
	
	static function getInstance() {
		return new Test();
	}
	
	public function printMsg($msg) {
		print $msg;
		return $this;
	}
	
	public function arg() {
		print 'I AM AN ANGRY METHOD!';
		return $this;
	}
}

Test::getInstance()->printMsg('this is a test')->arg();

Of course I do more interesting stuff with it than prints…model stuff and what have you.