RE: [PHP] Method chaining off constructors

From: Date: Fri, 06 Jun 2008 14:57:34 +0000
Subject: RE: [PHP] Method chaining off constructors
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-275095@lists.php.net to get a copy of this message
> -----Original Message----- > From: Christoph Boget [mailto:christoph.boget@gmail.com] > Sent: Friday, June 06, 2008 9:45 AM > To: PHP General > Subject: [PHP] Method chaining off constructors > > Is there a reason why you can't do method chaining off of constructors? > > Consider the following class: > > class bob > { > public function __construct() > { > echo 'Constructor()'; > } > > public function one() > { > echo '->one()'; > return $this; > } > > public function two() > { > echo '->two()'; > return $this; > } > } > > This works: > > $bob = new bob(); > $bob->one()->two(); > > whereas this doesn't. > > $bob = new bob()->one()->two(); > > Why? I thought constructors returned the object? It's been a while since I've played with objects in PHP, but couldn't you just add the line: return $this; ...to the end of your __construct() function? Sorry if this is obtuse of me to say, I just thought maybe the answer was that simple and you're like I am--you've been staring at a tree for so long, racking your brain, that you forget about the forest altogether. :) Todd Boyd Web Programmer

« previous php.general (#275095) next »