PHP instantiate and call a method in one statement

PHP chaining instantiation

PHP doesn't allow you to construct an object and call a method at the same time. For example the following does not work:

$domain = new Website($id)->getDomain();

What we need to do is call a static method of the class which instantiates itself. For example:

class Website() { public function __construct($id) { $this->id; //some code which grabs the websites details from a database } public function getInstance() { return new Website(); } public function getDomain() { return $this->domain; } } $website = Website::getInstance(); //same as $website = new Website();

Don't forget to put any parameters that are needed:

class Website() { public function __construct($id) { $this->id; //some code which grabs the websites details from a database } public function getInstance($id) { return new Website($id); } public function getDomain() { return $this->domain; } } $website = Website::getInstance($id); //same as $website = new Website($id);

Now we're free to instantiate a new object and call one of its methods immediately

class Website() { public function __construct($id) { $this->id; //some code which grabs the websites details from a database } public function getInstance($id) { return new Website($id); } public function getDomain() { return $this->domain; } } $domain = Website::getInstance($id)->getDomain();

Once we have this freedom and flexibility we can chain our PHP methods together to initialise our values:

$website = Website::getInstance($id)->add($homePage)->add($contactPage)->add($aboutPage);