When to use static vs instantiated classes When to use static vs instantiated classes php php

When to use static vs instantiated classes


This is quite an interesting question -- and answers might get interesting too ^^

The simplest way to consider things might be :

  • use an instanciated class where each object has data on its own (like a user has a name)
  • use a static class when it's just a tool that works on other stuff (like, for instance, a syntax converter for BB code to HTML ; it doesn't have a life on its own)

(Yeah, I admit, really really overly-simplified...)

One thing about static methods/classes is that they don't facilitate unit testing (at least in PHP, but probably in other languages too).

Another thing about static data is that only one instance of it exists in your program : if you set MyClass::$myData to some value somewhere, it'll have this value, and only it, every where -- Speaking about the user, you would be able to have only one user -- which is not that great, is it ?

For a blog system, what could I say ? There's not much I would write as static, actually, I think ; maybe the DB-access class, but probably not, in the end ^^


The main two reasons against using static methods are:

  • code using static methods is hard to test
  • code using static methods is hard to extend

Having a static method call inside some other method is actually worse than importing a global variable. In PHP, classes are global symbols, so every time you call a static method you rely on a global symbol (the class name). This is a case when global is evil. I had problems with this kind of approach with some component of Zend Framework. There are classes which use static method calls (factories) in order to build objects. It was impossible for me to supply another factory to that instance in order to get a customized object returned. The solution to this problem is to only use instances and instace methods and enforce singletons and the like in the beginning of the program.

Miško Hevery, who works as an Agile Coach at Google, has an interesting theory, or rather advise, that we should separate the object creation time from the time we use the object. So the life cycle of a program is split in two. The first part (the main() method let's say), which takes care of all the object wiring in your application and the part that does the actual work.

So instead of having:

class HttpClient{    public function request()    {        return HttpResponse::build();    }}

We should rather do:

class HttpClient{    private $httpResponseFactory;    public function __construct($httpResponseFactory)    {        $this->httpResponseFactory = $httpResponseFactory;    }    public function request()    {        return $this->httpResponseFactory->build();    }}

And then, in the index/main page, we'd do (this is the object wiring step, or the time to create the graph of instances to be used by the program):

$httpResponseFactory = new HttpResponseFactory;$httpClient          = new HttpClient($httpResponseFactory);$httpResponse        = $httpClient->request();

The main idea is to decouple the dependencies out of your classes. This way the code is much more extensible and, the most important part for me, testable. Why is it more important to be testable? Because I don't always write library code, so extensibility is not that important, but testability is important when I do refactoring. Anyways, testable code usually yields extensible code, so it's not really an either-or situation.

Miško Hevery also makes a clear distinction between singletons and Singletons (with or without a capital S). The difference is very simple. Singletons with a lower case "s" are enforced by the wiring in the index/main. You instantiate an object of a class which does not implement the Singleton pattern and take care that you only pass that instance to any other instance which needs it. On the other hand, Singleton, with a capital "S" is an implementation of the classical (anti-)pattern. Basically a global in disguise which does not have much use in the PHP world. I haven't seen one up to this point. If you want a single DB connection to be used by all your classes is better to do it like this:

$db = new DbConnection;$users    = new UserCollection($db);$posts    = new PostCollection($db);$comments = new CommentsCollection($db);

By doing the above it's clear that we have a singleton and we also have a nice way to inject a mock or a stub in our tests. It's surprisingly how unit tests lead to a better design. But it makes lots of sense when you think that tests force you to think about the way you'd use that code.

/** * An example of a test using PHPUnit. The point is to see how easy it is to * pass the UserCollection constructor an alternative implementation of * DbCollection. */class UserCollection extends PHPUnit_Framework_TestCase{    public function testGetAllComments()    {        $mockedMethods = array('query');        $dbMock = $this->getMock('DbConnection', $mockedMethods);        $dbMock->expects($this->any())               ->method('query')               ->will($this->returnValue(array('John', 'George')));        $userCollection = new UserCollection($dbMock);        $allUsers       = $userCollection->getAll();        $this->assertEquals(array('John', 'George'), $allUsers);    }}

The only situation where I'd use (and I've used them to mimic the JavaScript prototype object in PHP 5.3) static members is when I know that the respective field will have the same value cross-instance. At that point you can use a static property and maybe a pair of static getter/setter methods. Anyway, don't forget to add possibility for overriding the static member with an instance member. For example Zend Framework was using a static property in order to specify the name of the DB adapter class used in instances of Zend_Db_Table. It's been awhile since I've used them so it may no longer be relevant, but that's how I remember it.

Static methods that don't deal with static properties should be functions. PHP has functions and we should use them.


So in PHP static can be applied to functions or variables. Non-static variables are tied to a specific instance of a class. Non-static methods act on an instance of a class. So let's make up a class called BlogPost.

title would be a non-static member. It contains the title of that blog post. We might also have a method called find_related(). It's not static because it requires information from a specific instance of the blog post class.

This class would look something like this:

class blog_post {    public $title;    public $my_dao;    public function find_related() {        $this->my_dao->find_all_with_title_words($this->title);    }}

On the other hand, using static functions, you might write a class like this:

class blog_post_helper {    public static function find_related($blog_post) {         // Do stuff.    }}

In this case, since the function is static and isn't acting on any particular blog post, you must pass in the blog post as an argument.

Fundamentally this is a question about object oriented design. Your classes are the nouns in your system, and the functions that act on them are the verbs. Static functions are procedural. You pass in the object of the functions as arguments.


Update: I'd also add that the decision is rarely between instance methods and static methods, and more between using classes and using associative arrays. For example, in a blogging app, you either read blog posts from the database and convert them into objects, or you leave them in the result set and treat them as associative arrays. Then you write functions that take associative arrays or lists of associative arrays as arguments.

In the OO scenario, you write methods on your BlogPost class that act on individual posts, and you write static methods that act on collections of posts.