Last active
August 29, 2015 14:05
-
-
Save addshore/04863ade4960c5616135 to your computer and use it in GitHub Desktop.
PHP Returning $this from __construct
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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