Alex Rivera | Logout

Best practices for static constructors

Asked 2011-03-20T11:31:10.383
27

I want to create an instance of a class and call a method on that instance, in a single line of code.

PHP won't allow calling a method on a regular constructor:

new Foo()->set_sth(); // Outputs an error.

So I'm using, if I can call it that, a static constructor:

Foo::construct()->set_sth();

Here's my question:

Is using static constructors like that considered a good practice and if yes, how would you recommend naming the methods for these static constructors?

I've been hesitating over the following options:

Foo::construct();
Foo::create();
Foo::factory()
Foo::Foo();
constructor::Foo();
Edit
Report

1 Answer

4

These are called creation methods, and I typically name them createXXX() such as createById() or createEmptyCatalog(). Not only do they provide a nice way to reveal the different intentions of an object's constructors, but they enable immediate method chaining in a fluent interface.

echo Html_Img::createStatic('/images/missing-image.jpg')
        ->setSize(60, 90)
        ->setTitle('No image for this article')
        ->setClass('article-thumbnail');
answered 2011-03-23T08:13:05.940

Your Answer