Michael A Heap

Chaining in PHP

May 28, 2009 Code, PHP2 Comments on this article

I was just flicking through Tweetdeck when I noticed a tweet by @F1LT3R that was a link to a pastebin snippet. I was curious, so I followed the link and was presented with the following code:

If (isset($resistance) && $resistance->leader == "John Connor") {
	$resistanceDeath = $TemporalEngine->SetTimeCoords(strtotime('Birth of John Connor'))->AcquireSubject(new Terminator)->Transport();
}

if (!$resistanceDeath) {
	$resistanceDeath = $TemporalEngine->SetTimeCoords(strtotime('Birth of John Connor + 12 years'))->AcquireSubject(new Terminator)->Transport();
}

Now that's quite entertaining on it's own, but it got me thinking. I love how you can chain items in jQuery, and I was wondered if it would work in PHP. A quick test showed me that it would! Not too sure how useful it'd be, but it's quite interesting all the same. Here's my quick mockup code:

class chain {
	function setStr($s){
		$this->s = $s;
		$this->response = $s;
		return $this;
	}
	function length(){
		$this->response = strlen($this->s);
		return $this;
	}
}

$c = new chain();
echo $c->setStr("HEH")->length()->response;

It's a very trivial example, but I'm sure someone out there would be able to think of a use for it.

Related posts:

  1. iTunes Library Parser

Tags: , , ,
« »

Caius at 12:50 am on May 29, 2009

Technically this is more something you can do with objects rather than just PHP. Same thing will work in Objective-C or Ruby for instance. (And in fact is quite prevalent in both languages.)


John ORourke at 7:53 am on June 2, 2009

There is a hidden advantage to this too – returning the object from all its methods forces you to use proper exception throwing to handle errors, because you can no longer return a special value to indicate errors. However in PHP the built in functions don’t throw exceptions, so you have to detect their return values and throw exceptions yourself.



Leave a Reply