News Feed
Sections




News Archive
Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Mathias Verraes:
Named Constructors in PHP
June 13, 2014 @ 09:42:15

Mathias Verras has a new post to his site about an idea he calls "named constructors". This method uses static factory methods to simulate the idea of a constructor and initialize the object.

PHP allows only a single constructor per class. That's rather annoying. We'll probably never have proper constructor overloading in PHP, but we can at least enjoy some of the benefits. Let's take a simple Time value object. Which is the best way of instantiating it? The only correct answer is "it depends".

His example shows the typical constructor creation with variable arguments, but points out that this can get messy quickly. His other method, the factory methods as "constructors", can make for a cleaner interface and makes the class more flexible. They make the object able to be initialized with different types of values and even satisfies the Single Responsibility Principle. He goes through a few examples using his "Time" class, showing how different "constructor" methods can be used to handle inputs ranging from a normal hour/minute format out to a "from minutes since midnight" value.

0 comments voice your opinion now!
named constructor factory method static tutorial time

Link: http://verraes.net/2014/06/named-constructors-in-php/

blog comments powered by Disqus

Similar Posts

Marcelo Gornstein's Blog: Writing PHP applications with Doctrine2 as ORM and Ding as DI container

DevShed: Positioning Strings with the show_xy() Method in PDF Documents with PHP 5

PHPMaster.com: Sending Email with Swift Mailer

Developer.com: Build Multi-lingual Websites With the Zend Framework

Alison Gianotto: Check User-Submitted URLs for Malware and Phishing in Your Application


Community Events





Don't see your event here?
Let us know!


composer introduction podcast release security interview update voicesoftheelephpant language community symfony package version framework mvc opinion series library laravel tool

All content copyright, 2014 PHPDeveloper.org :: info@phpdeveloper.org - Powered by the Solar PHP Framework