PHP !== Java

(This post originally appeared as part of the 2008 PHP Advent calendar)

Java has its place. Maybe it has many places. I’m OK with it being on your phone, in your refrigerator, and on my bank’s web site. I’m even OK with it making another play to be in browser applets. However, I’d really prefer if you kept it out of my PHP. I am seeing more and more PHP written as though it was Java with dollar signs. I think this is misguided.

PHP has its own pragmatic beauty. It does not try to check off enterprise buzzwords or be all things to all people. It does not try to be pure, driven down an organized roadmap, or marketed by a single owner. But it does get stuff done. Written well, it can be brief without being terse, and tidy without being restrictive. In its normal form, it will just work without significant planning and without consuming significant resources.

Using a spoken or computer language effectively is not just a matter of learning your language’s syntax and vocabulary. It is also about learning the quirks and idioms unique to that language, and using it in normal ways so that others don’t have to work to hard to understand you.

Translating the French Il pleut des cordes literally into English as It is raining ropes is nonsense. Literally translating the equivalent English Idiom It is raining cats and dogs into most other languages probably also results in nonsense. Potentially syntactically correct nonsense, potentially decipherable nonsense, but nothing that will flow naturally in conversation with a native speaker.

Translating Java literally into PHP gets similar results.

Here is a Java implementation of the singleton pattern:

public class Singleton
{
  private static Singleton myObject;

  private Singleton()
  {
     // Providing a constructor to eliminate default public one.
  }

  public static Singleton getInstance()
  {
    if (myObject == null) {
    myObject = new MyObject();
  }

    return myObject;
  }

  public Object clone() throws CloneNotSupportedException
  {
    throw new CloneNotSupportedException();
  }
}

In case you are not familiar with it, the singleton pattern is a general solution to many situations where you want only one instance of a particular class. Examples might include a database connection, a logger, or many user interface components.

Scatter a few dollar signs and make a few minor changes, and you get a valid PHP implementation:

class Singleton
{
  private static $myObject;

  private function Singleton()
  {
    // Providing a constructor to eliminate default public one.
  }

  public static function getInstance()
  {
    if (! isset(Singleton::$myObject) )
    {
      Singleton::$myObject = new MyObject();
    }

    return Singleton::$myObject;
  }

  private function __clone()
  {
  }
}

A native PHP speaker is much more likely to implement the same pattern as follows:

global $myObject;

if (!isset($myObject)) {
  $myObject = new MyObject();
}

Unfortunately, choosing this example might divert attention from the point I am trying to make. Global variables elicit a knee-jerk reaction in many people for a number of reasons, many of them good. In reality, more elaborate implementations of the singleton pattern deserve most of the same criticisms. Singletons are the object-oriented implementation of global variables.

PHP has always taken well-understood things from other languages. Why create new function names if people already know the names of the underlying C functions? Why not copy Java’s object system that many people already grasp? Why not offer Perl inventions that people find useful? But, the broth that this mix of ingredients creates has a unique flavor. It is not C, nor Java, nor Perl, and trying to program as if it is will probably leave you both missing the appeal of PHP and frustrated at the differences.

Like putting a hippo in a tutu, or a ballerina in a swamp, trying to force a language to be something it is not looks silly, works poorly, and gets leeches in your slippers.

OK, maybe I lied about the leeches.

19 Responses to “PHP !== Java”

  1. A PHP Vet Says:

    Dude, what the heck is wrong with you??

    I just saw your comment :

    “An experienced PHP developer is much more likely to implement the same pattern as follows:”

    ….

    “Unfortunately, choosing this example might divert attention from the point I am trying to make. Global variables elicit a knee-jerk reaction in many people for a number of reasons, many of them good. ”

    Are you insane? Are you on drugs? Are you seriously suggesting that experienced developers use and like Globals because globals have GOOD parts to them?

    Seriously, the only “experienced” developer that I know of who still uses Globals, are novices. You need to get with the times man.

  2. Sheridon Says:

    Very insightful article and great example using both the Singleton implementation and even the global object. Your examples regarding phraseology translation in various languages are quite illustrative.

    Although you pointed out the use of the global variable was merely exemplary, it’s unfortunate that some people would focus on that critically in their need to just have something to say.

  3. ferdhie Says:

    I’m so totally agree with you, why writing so much lines only for a singleton while with a simple 3 lines of code, you get the job done.

    Great articles

  4. Ben Says:

    You never write the DP style singleton in Java. If properly synchronized (which you failed to do), its slow under high contention. You always use the fact that class loading is thread-safe.

    // eager
    public final class Singleton {
    private static final Singleton instance = new Singleton();

    private Singleton() {}

    public Singelton getInstance() {
    return instance;
    }
    }

    // lazy
    public final class Singleton {

    private Singleton() {}

    public Singelton getInstance() {
    return Holder.instance;
    }

    private static final class Holder {
    static final Singleton instance = new Singelton();
    }
    }

    However, Java developers have moved behond even these approaches. We now use Spring (IoC containers) to wire a single instance to all clients, thus avoiding such tricks entirely.

  5. Von hinkenden Vergleichen und Erfahrenen PHP-Programmierern | Der PHP Hacker Says:

    […] Blog zählt nichtmal 10 Artikel, und ich muss schon mit dem Stänkern anfangen . Mir fiel heute ein Artikel von Luke Welling in die Hände, der so unglaublich schlecht ist, dass man ihn schon wieder verlinken muss. Konkret […]

  6. unset Says:

    @Sheridon: Maybe Luke just want to express his antipathy for the presumed java trend in php applications. But Luke also just came up with a single example - moreover a really bad one.

    @fredhie: I think it will count up to more than these three lines. These three little lines will show up several times in you application: Everytime you need you global object. Since you can extends classes, you can extend a Singleton class, too. If you want to implement more global objects, you need to type your three little lines slightly modificated over and over again.

  7. Pekka Says:

    @PHP Vet: Read the sentence again. Luke is saying exactly the opposite of what you think he is saying.

  8. Mjomble Says:

    Hmm. Why use separate classes for MyObject and Singleton (and leaving MyObject’s constructor public so it could still be misused) if you could just add singleton behavior to the MyObject class itself?

    class MyObject
    {
    private static $singleton;

    public static function getInstance()
    {
    if (!isset(self::$singleton))
    {
    self::$singleton = new self();
    }

    return self::$singleton;
    }

    private function __clone()
    {
    }

    private function __construct()
    {
    // MyObject’s regular constructor made private
    }

    }

    And then if you need to use that in a large number of different places, you end up with lots of calls to MyObject::getInstance(); instead of the “simpler” 5-line version you suggest :)

  9. Mjomble Says:

    (Sorry about the indentation, the comment system ate it)

  10. ajclose Says:

    For a second there Luke I thought you were talking about Perl… ;)
    And thanks for teaching me a new French expression!

  11. Mart Says:

    People, you should read this blog entry http://www.stubbles.org/archives/56-How-to-get-a-Singleton-right.html

  12. Richard C Says:

    Actually Singletons in java are now (since 1.5) written as enums. As best practice.

    enum Singleton{
    instance;

    public static Integer getCount(){
    return 30;
    }
    }

  13. void star Says:

    An ironic linguistic example given that one explanation for the phrase “raining cats and dogs” is that it is a mis-translation of the French word “catadoupe”, meaning “waterfall”.

  14. Roderick Kar Says:

    This may not be the most appropriate place to post my question. I bought a kindle edition of your 4/e php and mysql web development. I have registered it on informit but I couldn’t find where can I download the contents that come with the CD that accompanies the physical book.

  15. Robin Says:

    I think the main thing with using a singleton when a (what’s the word?) not-singleton will do is probably just a case of “I’m doing this because it’s the right thing”

    If the thing works, why try to fix it, eh?

  16. Helga Says:

    I don’t understand why is everyone discussing Singleton implementation. I totally agree with what I believe is the true intent of this post, which is the attempt to transform a language in to something that is not “in it’s nature”. I will have to make my opinion humble for I have no more than 1,5 year experience in codding… Though the author gives more physical examples… I’d give another more… ethereal? One usually speaks according to context. farmers have their dialect, politicians have their dialect.. And though there may be farmers who can speak like politicians, and politicians who can speak like farmers. Most politicians and farmers will not be able to switch parts.. what is happening is that universities don’t teach php, in fact they don’t teach any script language other than javascript… and quite in the “demonstration by intimidation… obvious” style. but they do teach java, and c++ and c#. All oop languages.. strongly typed. So when these coders “hit the streets” they don’t speak script… they speak oop. And because they don’t care about nature, nor do they understand beauty they keep speaking oop. The problems arise from the complexity one adds without necessity. But that complexity could only be perceived by an experienced php programmer or a concerned oop developer. For a farmer will always feel greater sympathy for a politician that speaks like a farmer.. The question here really is. Can we make all those farmers speak politician? will they be willing to? won’t they create more problems while working with an unfamiliar environment? Hopefully the frameworks will continue to be loyal to the language nature.. and one can rely on those. * my two cents…*

  17. Lamonica Sedrakyan Says:

    Outstanding site, I really discovered it to be thought prevoking. I am looking forward to returning again to examine what is recent.

  18. Jonas Says:

    New Faucet

    Visit my page youtu.be - Jonas,

  19. business intelligence tools Says:

    It’s no question which this can be a popular domain for companies
    to place a call. Indeed there aren’t also many sites similar to this which
    come up in the market, with not already been purchased by Apple
    themselves.

    Feel free to surf to my website :: business intelligence tools

Leave a Reply