Richard Keller
Richard Keller

Reputation: 1952

Static classes vs class member access on instantiation

In versions of PHP prior to 5.4 I used static classes to instantiate an object and immediately call the required function, for example:

$result = Foo::init()->bar();

In the above example, the static function init() simply instantiates the class in which it is contained and returns it as an object. This provides method chaining functionality and allows me to immediately call bar(), all in one line of code. The static function init() looks something like this:

static public function init() {
   $object = new self();
   return $object;
}

Now PHP 5.4 has added support for class member access on instantiation, and instead of using a static class I can now do the following:

$result = (new Foo)->bar();


My question: Is my old way of using static classes bad, and if so, why? Now that PHP supports class member access on instantiation, is this the more correct way of accessing class members immediately after object instantiation?

Upvotes: 2

Views: 359

Answers (2)

Wrikken
Wrikken

Reputation: 70460

If that's all your ->init() does, you can get away with (new Foo)->bar();, but when you go the Dependancy Injection route, you most likely want to create some kind of Factory to 'inject those depedencies' on instantiation. The factory may a full fledged instantiated object, or just a static method for starters, but fact of the matter is: if you need outside access injected into your class (database handlers, settings) now or possibly in the future, and you don't want to abuse globals or singletons (which are kind of globals...), you'll be very thankfull you have 1 method / class where your objects are instantiated rather then sprinkled through the codebase.

Upvotes: 1

Ry-
Ry-

Reputation: 224886

Yes, the new way is more correct, so use it if you're able. The way you had it before isn't "bad", though; it's a clean, simple solution to a frustrating problem.

Upvotes: 3

Related Questions