PHPundamentals Series: A Background on Statics (Part 1 on Statics)

May 6th, 2010 § 11 comments

Just beyond reading the title, you’ve more than likely come to this article as the curious yet uninformed, the mad and raving lunatic, or as an enlightened one. Static class members (from here on called simply, “statics”) in PHP conjure both the best and worst in developers for a variety of reasons. In part 1 of this series of articles on statics, we’ll explore some background to get a better understanding of statics in PHP.

Some Static Background And Understanding

Before we can move into the arguments that surround statics, we first need to understand what they are in the context of PHP.  The core of the PHP language and runtime can draw some pretty big corollaries from the Java/JVM and C#/.NET language platforms. The biggest, and most important for the purposes of this article, is PHP’s object model. Like Java and .NET, PHP follows a class-based, single-inheritance, multiple-interface model- a tenet described by the grandfather of OO languages: smalltalk. Of course, PHP applies its own “perspective” when it comes to the actual implementation details in that of typing, casting, mixed-paradigm usage, and so on; but the foundation for the object model is clearly defined.

That said, it is easy for the PHP community to draw comparisons and, more importantly, “borrow” best practices from both the Java and .NET communities. We certainly have borrowed our fair share with regards to development time tools, infrastructure tools and design patterns. Over the past 5 to 7 years, there has been an increasing adoption of best practices and patterns from the enterprise Java community, particularly in the form of two major texts: GoF and PoEAA. The GoF (Gang of Four) text primarily discusses best practices in the form of code structure and reuse: factory, singleton, adapter, composite, facade, iterator and observer to name a few. PoEAA (Patterns of Enterprise Application Architecture), on the other hand, attempts to solve higher order problems, particularly architectural problems at the application layer: MVC, Page Controller, Front Controller, Domain Model, Table and Row Gateway, and so on. While the examples are primarily executed in Java, they are structurally similar when implemented in PHP, so much so that PHP developers can read the Java examples as pseudo-code. This is what makes these patterns so applicable and thus popular in the PHP community.

Since we now know where these usage patterns originated, we should have a look at the target language platform: PHP. The key concept which delineates the PHP platform from the JVM and .NET platforms, is that PHP by default assumes a shared-nothing architecture. What does this mean? It means out of the box, PHP is not a persistent application platform. PHP’s runtime is built around the notion of primarily solving the web problem. In turn, since the web is request driven, you might say that an application written in PHP is also request driven. Put another way, the scope of your application is bound to a single request. The shared-nothing aspect means that the state of the application is built-up and torn-down upon the start and completion of each request to your application. Conversely, Java and .NET offer a persistent application stack which means the application’s state exists separate from the requests that come in via the web server. So, in PHP, the many requests each contain a single running instance of your application. In Java/.NET, the single application running handles the many requests.

Statics in Analogies

Still don’t get it? Let’s talk in a couple of analogies. Let’s assume we’ve built a basic application with the “out-of-the-box” technologies offered; one built on top of PHP and the other built on top of Java (or .NET, you can choose.) With your Java/.NET application, if a request is never received from your web server, the application is indeed still running. In PHP, if a request is never received from your web server, the application has NEVER run. The runtime of a Java/.NET application might be hours or days, whereas the runtime of a PHP application is a long as it takes to service the request. This analogy’s mileage may vary, and it is surely intended for demonstrative purposes. You could inject any number of monkey wrenches into it, but for all intents and purposes- it’s correct and it works.

Understanding the full scope of an applications runtime state is the most important aspect into understanding the role of static class members in OO programming. Static class members live as long as the application runtime is valid and alive. What this means it is that any class member state that has been set during any operation during the applications runtime will persist until the application ceases to exist. Looking back at our main platform differences, we can see that in the Java/.NET platform, statics members created in the scope of an application layer will be around until someone pushes the “shutdown” button on that application. This could mean a static member or static state is persisted for hours, days, or even longer. Like these persistent application stacks, PHP will destroy any static members and state at the end of the applications lifecycle. Unlike these persistent application stacks, the application lifecycle ends with the completion of a web request. This means that static members and static state in PHP, for the average web application, sticks around for seconds or less and is only valid in the context of a single web request.

Statics in Pictures

Still don’t get it? Lets have a look at a few images to better explain these concepts.

The following images will attempt to explain the various layers of a web application, one from the perspective of the JVM/.NET platform, the other from the perspective of the PHP platform. (For all intents and purposes, the PHP platform could also be any scripting language executed by an apache module or fastcgi.)

The green layer is the web server layer, this is the process that will attach to port 80 and listen for requests. The blue layer represents the application process itself. This layer is responsible for global application state and class-based static state. The orange layer is a request which comes in from the web, this is typically what we’ve called a page request. Inside of each web request is the yellow layer, which represents the page-lifecycle. In terms of the application, this is where all of the request specific application routines happen including page startup and business logic.

Contrasted against …

The most important thing to take away from these images, particularly with respect to understanding statics, is the blue layer, or the layer that best represents the scope of globals and static members. This is the heart of what is meant by a “shared-nothing” architecture. It is this key difference that affects how we architect the code for our web applications.

In the next article in this series, we’ll have a look at PHP’s application architecture in greater detail and how it solves problems that might arise from a shared-nothing style architecture, why this architecture is arguably better for the web and cloud based services, but most importantly, how statics fit into this paradigm.

Tagged , , ,

  • gggeek

    Excellent article! Clear and to the point.

    I’m eager to see the follow ups, as I think they will help a lot in dispelling common myths (or, better, “coding best practices that do not apply anymore in a page-based paradigm and yet everybody is bound to blindly follow lest he becomes a target for daily wtf jokes”), such as ‘global variables are evil’

  • [ this is jerry ]

    Great article, Ralph. Thanks for educating us.

    What I always find interesting is how individual coders solve issues that arrise because of this. For example, MaxMind uses shared memory (

  • Kevin Bruce

    Thanks for this article. Having really only worked in PHP, it’s good to know the differences between the major web languages. It explains allot about how we, as PHP developers” have to “fake” a persistent state with sessions, cookies and database storage in order to have a consistent state on a visitor’s return visit.

  • Mandi

    Very good starting article! Can’t wait to see how the series of these articles continues :)

  • Bruce Weirdan

    > Still don’t get it?
    Don’t get what exactly? What is the point you’re trying to drive home?

    • Ralph Schindler

      Hey Bruce, I basically mean “Do you not get how they work?”. The point of this article is to fully understand the scope of static members. Originally, this article was much longer, but when I realized how long this way, I decided to make a series of them. This is just a background article. The next articles will attempt to describe the persistence problem we have in PHP, look at the solutions.. then move into the “static argument” – what are they good for? Are they really as evil as globals? And, of course, we’ve all heard the expression: “Singletons are evil, never use them..”, we’ll discuss where that argument came from and how it applies to PHP.

      Hopefully you’ll stay tuned, I’ll try to deliver the point in a few days- I am just laying some ground work.


  • rafaelxy

    Great article, I’m looking forward to read the next one =)

  • George Mauer

    Ok, I’ll bite…

    You deserve a berating for not mentioning the biggest thing about statics: (public) statics have no limitations on visibility. Fully allowing that I might be missing something, but statics in PHP are conceptually equivalent to global variables. Presumably you’re going to argue that that is not necessarily bad – and from a memory management perspective you’re right. From a making-your-application-maintainable perspective globals – as you know – are a nightmare. Especially since its usually perfectly possible to limit the scope of your variables. Heck, with the shared-nothing thing, I’ve never quite understood why php went head-first into OO, a functional paradigm with tight immutability rules seems like a much better fit.

    Now, regarding Java/.Net – statics are generally allowable only in situations where you do not persist state such as helper methods or DSLs. Even there they are discouraged. The only place I would ever see a static state in a well-constructed C# application (stupid ASP.Net framework nonsense aside) is when using a Service Locator – and even that I’m generally uncomfortable with as there is almost always a better way.

    If you need to persist state – whether it’s data, objects, or whatever – then persist it correctly. Use MySql, or Sqlite, or memcached, or CouchDB, or who cares. Statics are a tempting way to do it, but its way too easy to get into trouble with them. Yes, the fact that PHP limits them to the scope of the request limits their damage potential but reading your average PHP code is difficult enough – please don’t recommend people to make it harder.

  • Giorgio Sironi

    I disagree with calling ‘static&global’ what is really an application scope. :)
    The important difference is between the shared-nothing architecture of PHP applications and the shared application scope of a Java Servlet application, but there’s nothing inherently static in them.
    In fact, a good rule to see if you’re doing things right is the ability to run two identical applications in the same JVM. Global [variables] are hidden dependencies; static [variables, method, classes] are similarly hidden dependencies.
    An example of this is Zend Framework’s Zend_Test component, which because of the singletons usage for sessions and front controller, has to reset the various components manually between tests, instead of simply creating a new application object.

  • Dirk Louwers

    “If you need to persist state – whether it’s data, objects, or whatever – then persist it correctly. Use MySql, or Sqlite, or memcached, or CouchDB, or who cares.”

    I couldn’t disagree more. Apart from the quirky UTF support in PHP5 the lack of a true application scope is something I miss most! In most of my applications there is plenty of data that is already properly persisted, like in a configuration file or annotations for instance. Often parsing this data on a per request basis is unacceptable from a performance standpoint. Serializing this data alleviates the pain somewhat but still carries a performance penalty. The best solution I’ve found so far is translating such data to PHP classes so that in combination with an opcode cache the data can be made available as quickly as possible, but this is by far more contrived than using application scope for this. Just my two cents.

  • phpcurious

    Great article, when are you going to publish the follow up? Any solution on how to remedy the issue posed by PHP architecture?

What's this?

You are currently reading PHPundamentals Series: A Background on Statics (Part 1 on Statics) at Ralph Schindler.