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.

78 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

  12. Richard C Says:

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

    enum Singleton{

    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 - 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

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

  20. 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

  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

  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

  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:

    […] Posted on November 7, 2014 […]

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

    […] […]

  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:

    […] […]

  34. Valentin Says:

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

  35. 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:

    […] […]

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

    […] […]

  38. Says:

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

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

    […] […]

  40. Nike Sapatilhas Says:

    Para a home page está se tornando um desperdício de tempo. Eu quero fazer a base da cobertura de espessura. No filme de slide cor, os acopladores corante atribuem às áreas não expostas. Há muitos exercícios de mama ao redor, e é sempre bom começar com aqueles que você acha que são fáceis o suficiente para que você possa fazer.James ‘Jamie’ Jones é um estudante de graduação de psicologia pesquisa na Universidade de Te

  41. Nike Tenisky Medzi najčastejšie a najspoľahlivejšie zdroje sú | Indo German School Says:

    […] […]

  42. Nike Air Max Thea Nz CSS | Indo German School Says:

    […] […]

  43. Nike Air Max Thea Nz Web integration|plugin|incorporation|intergrated | Indo German School Says:

    […] […]

  44. tels que ceux résultant de traductions Nike Talon Suisse | Indo German School Says:

    […] […]

  45. Parajumpers Solde ^ | Indo German School Says:

    […] […]

  46. Says:

    Excellent post. I used to be checking constantly this weblog and I am impressed!
    Very useful information specifically the final phase :)
    I deal with such information a lot. I used to be looking for this certain information for a long time.
    Thanks and best of luck.

  47. Share Photo, Ideas and Comments to People » during a hearing in 1992″ Michael Kors Purses Uk Says:

    […] […]

  48. Share Photo, Ideas and Comments to People » Nike Air Max Thea Nz “ Says:

    […] […]

  49. kamen oblutak Says:

    Colorful Mexican tiles set on a plain wall can enhance a Spanish Southwestern theme.
    If your ceiling is over 9 feet, paint it one shade darker than the wall color.
    A stone restoration professional can restore the polish.

  50. izrada sajta wordpress Says:

    The listing is made in on the entire top
    listing sites available including Google, Yahoo etc. It has also been determined that responsive
    designs usually take almost as long as desktop versions to load
    on many mobile devices, so the claim of faster loading is not always correct.

    This has given birth to a new genre of digital services - Web design and web development services.

  51. Jonathan Says:

    Keep these types of posts coming

  52. Share Photo, Ideas and Comments to People » Parajumpers Solde PAR LE me ti de la cr ea tio n des Etats de la ville Says:

    […] […]

  53. auto skola beograd Says:

    It will give you a fine advantage in choosing a driving school that will
    give you the fine advantage and potential. Whether you
    are an experienced driver or a newbie, joining a driving school in Seattle will be of
    benefit to you. When drivers are taught correctly, they automatically assess
    the whole lot involved.

  54. weight diet Says:

    Every weekend i used to pay a quick visit this web site, as i want enjoyment, as this this website conations actually pleasant funny data too.

  55. rent apartments belgrade Says:

    Serbia is a country that once was a part of Yugoslavia, and it is situated in Southern Europe.

    Banja Vrujci is well known base for the preparation of many sports clubs.
    With jagged coastlines, sandy beaches and lush, mist-shrouded forests, Vancouver
    Island’s west coast looks more like a scene from
    a fantasy movie than anything else - if of course, the fantasy movie had
    wicked big waves.

  56. prodaja mobilnih telefona Says:

    The phone can be connected through Bluetooth
    and micro USB support. This is the reality everyone has to face in the presence of cell phones in class rooms.
    With some many models from which to choose, it can be
    easy to rush into making a selection without looking at everything that is

  57. ugradnja staklenih prizmi Says:

    Most man-made electromagnetic fields are either 60 Hz fields as in America
    or 50 Hz in Europe and Russia. Unfortunately, only few recollect
    a saying that everything old is new again. A brightly coloured wall will fit
    in aptly in a kids’ room.

  58. Share Photo, Ideas and Comments to People » Fadan Longchamp Bruxelles 46 pour cent à 46 pour cent Pretty Says:

    […] […]

  59. in 2002 Nike Blazer Shoes | JMSred Says:

    […] […]

  60. Steel Toe Press – Timberland Boots Finland kaikki tunnin bileet Says:

    […] […]

  61. Share Photo, Ideas and Comments to People » Hollister Outlet since sack totals were recorded for teams Says:

    […] Posted on January 18, 2015 […]

  62. iznajmljivanje apartmana beograd Says:

    Plus, when you arrange to have several friends come along,
    the price can be split. The strategic and unique Dubai architecture with magnifying power
    of high standard of facilities including luxury, comfort,
    privacy and last but not the least, efficient staff services
    that force a new visitor to plan a re-visit to
    Dubai. Management companies will collect rent, arrange for any maintenance necessary and
    keep things running smoothly.

  63. Share Photo, Ideas and Comments to People » der Staat Subunternehmen Vorstand scheint bereit Oakley Frogskin Says:

    […] […]

  64. and geothermal ventures Cheap Ray Ban Sunglasses Uk | Indo German School Says:

    […] […]

  65. and geothermal ventures Cheap Ray Ban Sunglasses Uk | Indo German School Says:

    […] […]

  66. shaadi Says:

    At the same time, me and my pals were amazed by the number of black women white
    men couples. He enjoys physical culture, reading up on the
    great strongmen of old and chattering on about Asian religious philosophy.

    In their minds, prostitutes cannot say “No”, whereas these young girls can.

  67. yoga jewellery Says:

    Honesty: One of the first steps that you can take towards making
    your content more appealing is to be honest in your approach.
    Instead, climate-regulating clothing that helps you stay cool while controlling your
    body temperature is preferred. Wear comfortable clothing:
    It is necessary to wear comfy clothing whilst
    practicing yoga.

  68. youtube video downloader software Says:

    All downloads are saved to your download folder so you can change file names,
    convert web video to other formats and enjoy your video.
    com to create playlists of other people’s content that can be found on You - Tube.
    Being able to access Youtube in China with a proxy is, for the most part, the same as
    unblocking any other sites in China.

  69. Share Photo, Ideas and Comments to People » Cheap Pandora Rings Uk display Says:

    […] […]

  70. Louboutin Says:

    Being blessed with several children Adam, Harry, Robbie and Molly I will be also lucky to be hitched to Jackie, a most outstanding woman who has helped me to grasp that love, laughter as well as fun in the family is the most potent and enduring force that protects the human spirit via obliteration when faced with fear, pain and loss.However, acquiring this sense of contentment has been hard fought and seemed a hopeless dream six years ago.It was then that our world imploded while Adam our four y

  71. Joel Says:

    Hi there Dear, are you genuinely visiting this website regularly, if so then you will definitely take nice know-how.

  72. books Says:

    After kids books marriage, Kavita Sharma,
    after all. It had a good job quickly and get out.

    I will silence each one of many pleasurees here. Say it louder Okay, I asked
    all this.

  73. Share Photo, Ideas and Comments to People » Timberland Online Shop España Los archivos pueden ser imágenes Says:

    […] […]

  74. casque jet pour moto Says:

    These vehicles are not certified and offer almost no prottection to the inner liner or” custom motorcycle project you will need this to the helmet Mohawk. It mens all casque jet pour moto the nuances.
    The advanced fuel injection concept that make up the magazine when you are doing
    this is coming! They dont make anyy sense of security.

  75. renting apartments in belgrade Says:

    However, despite of the falling mortgage rates, many are still unable to purchase a home.
    Whether you are solo entrepreneurs, business professionals, small businesses and satellites of larger organizations, the real estate company will meet your needs.
    Check for maintenance issues when you rent home in Sacramento,

  76. visit my website Says:

    visit my website…

    Some Guy Ranting » Blog Archive » PHP !== Java…

  77. Ost und West Ray Ban Schweiz | Indo German School Says:

    […] […]

  78. says director NolanDirector Christopher Nolan Woolrich Woolen Mills Peacoa | Indo German School Says:

    […] […]

Leave a Reply