Created
February 26, 2011 15:14
-
-
Save bxt/845283 to your computer and use it in GitHub Desktop.
How to (and not to) use & create a PHP instance in the same line.
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
<?php | |
// echo (new Foo())->$bar; // fails | |
// PHP Parse error: syntax error, unexpected T_OBJECT_OPERATOR, expecting ',' or ';' | |
echo Foo::getI()->bar; //works | |
class Foo { | |
public function __construct() { | |
$this->bar="hello world\n"; | |
} | |
static function getI() { | |
return new static; | |
/* Above won't work in PHP<5.3. But in extending classes | |
* "new self" would still return an instance of Foo. | |
*/ | |
return new self; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment