Skip to content

Instantly share code, notes, and snippets.

@addshore
Last active August 29, 2015 14:05
Show Gist options
  • Save addshore/04863ade4960c5616135 to your computer and use it in GitHub Desktop.
Save addshore/04863ade4960c5616135 to your computer and use it in GitHub Desktop.
PHP Returning $this from __construct
// What can be done
class Foo {
function echo( $string ) {
echo $string;
return $this;
}
}
$foo = new Foo();
$foo->echo( 'foo' )->echo( 'bar' );
// What I want to do
class Foo {
function __construct() {
return $this;
}
function echo( $string ) {
echo $string;
return $this;
}
}
$foo = new Foo()->echo( 'foo' )->echo( 'bar' );
// Solution?
/**
* @return self
*/
public static function factory() {
return new self();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment