Skip to content

Instantly share code, notes, and snippets.

@bxt
Created February 26, 2011 15:14
Show Gist options
  • Save bxt/845283 to your computer and use it in GitHub Desktop.
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.
<?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