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.

39 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

  20. technologiik.blog.free.fr Says:

    Very excellent write-up. I stumbled upon your current web site in addition to want to mention that I have really adored browsing your current site discussions. In any case I’ll be opt-in on your nourish using this program . intending you’re all over again quickly!

  21. lebron 11 shoes Says:

    YouTube is world’s biggest video sharing web site, no one can defeat it. Every one add movies at YouTube then obtain embed code and post anyplace Some Guy Ranting » Blog Archive » PHP !== Java .
    lebron 11 shoes http://www.digitalenergyjournal.com/dej-ads/DEJshowNews.asp

  22. cheap jordans Says:

    Because the YouTube movies are posted here same like I also embed YouTube video code at my own website Some Guy Ranting » Blog Archive » PHP !== Java , as it is simple to take embedded code.
    cheap jordans http://www.pensacolaenergy.com/2011_essay/jordans.asp

  23. 2020 tax resolution In kudzu Says:

    of course like your website however you need to test the spelling on quite a few of your posts.
    A number of them are rife with spelling issues and I find it very bothersome
    to inform the reality nevertheless I’ll certainly come back
    again.

  24. the Association of Learning Providers 123789 - Palm Tree Community Says:

    […] started making the same unique nautical leads for our customers. via the prostaglandins. 123789 Best Answer 123456 After trying lots of disposables 123456 not operators […]

  25. 000000 Says:

    Insert garlic clove halves into slits. Place wood chunks on charcoal or lava rocks, and pour wine into water pan. While you may still find quality CRT televisions (tube style) being manufactured, the present television technology being pursued by manufacturers is Plasma Hd or LCD (Liquid Crystal Display). The primary advantages these two technologies offer includes small space taken up (mostly thorough) for a bigger picture, less heat (and for that reason less electricity consumed) generated for

  26. 000000 Says:

    Founded in 1889 Orkney Golf Club is definitely an 18 hole parkland course is just a short crossing or flight from the mainland which sets you upon a voyage of discovery. Situated in the Island capital of Kirkwall which comes from the Norse meaning Church Bay, Orkney is steeped in history and Kirkwall is a fairly bustling wee town.. There aren’t many things people do more often in 123789 a lifetime than eat. Therefore it is important that eating be pleasurable. You can always find the specially w

  27. shirt collar cats small Says:

    Hello, yeah this piece of writing is really pleasant and I have learned lot
    of things from it concerning blogging. thanks.

  28. Share Photo, Ideas and Comments to People » Moncler Jassen Dames zijn ernstige avatar in actiethriller’ Race 2 ‘ Says:

    […] http://lukewelling.com/2008/12/20/php-java/#comments Posted on November 7, 2014 […]

  29. Parajumpers Solde Les fusils de chasse surtout | Indo German School Says:

    […] http://lukewelling.com/2008/12/20/php-java/#comments […]

  30. victoria secret cyber Monday lululemon cyber monday 2014 - Palm Tree Community Says:

    […] victoria secret cyber Monday lululemon cyber monday 2014 Cont

  31. What is IRS Bank Levy - 2020 Tax Terminology Says:

    What’s up everyone, it’s my first go to see at
    this website, and article is actually fruitful in favor of me,
    keep up posting these types of content.

  32. Woolrich Tactical Pants Says:

    A relacionamentos, o conhecimento ea experiência que residem nas mentes dos funcionários são o que tornam uma organização. ‘Se parece que é possível estar pronto para ir no chão que a primeira semana de janeiro, então eu ficaria muito hesitante’, disse Lucas sobre o momento de uma votação da Câmara em sua extensão ‘. [Politico].. Ele tinha uma surpresa agradável e bastante molho. Me deparei com esta mesma pergunta há uns

  33. Parajumpers Solde Instant Article Factory | Indo German School Says:

    […] http://lukewelling.com/2008/12/20/php-java/#comments […]

  34. Valentin Says:

    I like reading a post that will make people think. Also,
    many thanks for allowing me to comment!

  35. www.sooperarticles.com Says:

    Hi there everyone, it’s my first pay a visit at this website, and article is truly fruitful in support
    of me, keep up posting such articles.

  36. Nike Air Max Baratas a | Indo German School Says:

    […] http://lukewelling.com/2008/12/20/php-java/#comments […]

  37. Nike Air Max In diesem Artikel werde ich wieder kommen | Indo German School Says:

    […] http://lukewelling.com/2008/12/20/php-java/#comments […]

  38. www.youtube.com Says:

    It’s hard to come by educated people on this subject, however, you seem like you know what you’re talking about!
    Thanks

  39. Parajumpers Solde un signet ou vous inscrire à des flux RSS | Indo German School Says:

    […] http://lukewelling.com/2008/12/20/php-java/#comments […]

Leave a Reply