Purpose of newInstance methods

Swift Mailer is a fantastic library for sending email with php. Discuss this library or ask any questions about it here.

Moderators: Chris Corbyn, General Moderators

Post Reply
kAlvaro
Forum Newbie
Posts: 2
Joined: Mon Apr 27, 2009 10:14 am

Purpose of newInstance methods

Post by kAlvaro »

I'm new to Swift Mailer but I've faced no problems so far (docs are really good).

Just curious about something... Why Swift_SmtpTransport::newInstance('example.com', 25) rather than good old new Swift_SmtpTransport('example.com', 25)? Is it a compatibility hack for PHP 4 or something like that?
AlexC
Forum Commoner
Posts: 83
Joined: Mon May 22, 2006 10:03 am

Re: Purpose of newInstance methods

Post by AlexC »

It allows you to do method chaining from the start, i.e:

Code: Select all

<?php
$foo = new Foo()->bar(); // Parse error
$foo = Foo::newInstance()->bar() // Will work just fine
?> 
To do it without the static newInstance, you'd need to do:

Code: Select all

<?php
$foo = new Foo;
$foo->bar();
?>
Edit: Swift Mailer 4 is also PHP 5 only, btw
kAlvaro
Forum Newbie
Posts: 2
Joined: Mon Apr 27, 2009 10:14 am

Re: Purpose of newInstance methods

Post by kAlvaro »

Ah, it's a clever trick indeed. Thank you.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: Purpose of newInstance methods

Post by Chris Corbyn »

Having the newInstance() methods also allows me some room to change the way the class is actually instantiated. It's a common design pattern called the Factory Pattern.

It's not documented, but you can use new ClassName() in place of the newInstance() method. The reason it's not documented is because at some point in the future I may make the constructor of some classes private/protected as part of a refactoring exercise.
Post Reply