Thinking About Programming

I Will Never Understand the Appeal Of PHP

Posted: 12/10/2006, Readers: 5229 Perm Link


Recently I was reading about a plugin for embedding adsense code automatically in blog posts, downloaded the code to see what it did, and found it to be php. Although I've never used php in any formal sense I have read enough to understand the "language". How PHP can be so popular is beyond me; the whole sense of encouraging all of your html, code, bindings, javascript, even sql (as in the below example) into a single file is a nightmare.

My first experience with JSP in its first year generated a similar reaction, the ability to embed html, javascript, java, and some odd xml in the same source file seemed convenient for about one day. The next day I couldn't make heads or tails out of what I had written the day before. I quickly came up with using a java class to hold all of the logic and only embedded the bare minimum in the jsp itself. Eventually the project shifted to the now common (but still fairly new at that time) full MVC approach. Splitting up the application into logical sections or layers proved the only way to manage and maintain development of a serious web application (we had something like 80-100 pages). Keeping the jsp file as clean as possible also made it easier to change the html design (which changed fairly rapidly over the initial 6 month development). This was also before tag libraries, so you still had to have some minimal java snippets, but at least it was fairly localized.

In PHP there is no alternative to embedding everything together; although you can certainly include other files, there are no real namespaces, so you can't really separate concerns without artificial complexity. Everything is interpreted (which I think is its main appeal) so changes appear directly without any need to compile or redeploy (anyone using traditional J2EE application servers like Weblogic will groan at that word, for me with Jetty it's about 2 seconds). It is appealing - for a while. Everyone I know who works with PHP admits that their application code gets uglier and less appealing over time even if they work hard at trying to keep order. Bugs and flakiness occur with greater frequency as portions of the code get less and less readable, especially as programmers turn over and are less familiar with the nest of language elements in each file. This can happen in any language but the rate of deterioration in PHP is way faster than the expected lifespan of the application.

In my last job the main storefront was written in PHP two years earlier, and listening to the programmer stuck maintaining the beast (not the original coder), the constant problems the storefront had, and the shear inability to make serious feature changes left no doubt it needed to be thrown out.

If there is anything that I have learned over the years is that you can make something run out of almost any technology. However I have also learned that just because something is easy and quick, it doesn't mean its going to stay that way. Very often an application spends far more time in maintenance than in initial development, so being able to jump in and understand some code you didn't write is really important and far more common than starting from scratch. With PHP (and ordinary JSP and ASP as well) I rarely see code that can be jumped into; most of the time you just want to throw it away and start over. With a proper separation of the application's layers/parts/components you can more easily understand the code and make changes without creating more bugs. Unfortunately with PHP (among others) it's usually beyond the developers to write easily maintainable applications as the language simply doesn't allow it.

Of course code in any language can be poorly written; I've seen my share of abysmal java code, objective-C, C++, C and even assembler. It seems to me that using a language well and avoiding its stupidities isn't always that easy (and many programmers have little discipline to learn how) but with PHP it seems the programmer benefits are far outweighed by its drawbacks. I bet the ultimate PHP coder can do a careful job of creating good code, but the problem is that the average coder is highly unlikely to due to the language itself.

function tracker()
{
  global $table_prefix, $wpdb;
  $table_name = $table_prefix . "mightyadsense";
  ?>
  <script language="JavaScript">
  var iFr;
  function log() { 
  var loca=document.location+"";
  if (window.status.indexOf('go to') == 0) 
  { 
  bug = new Image(); 
  if(loca.indexOf('?') > -1)
  {
    bug.src = loca + '&site=' + loca + '&target=' + window.status.substring(6) + '';
  }
  else
  {
    bug.src = loca + '?site=' + loca + '&target=' + window.status.substring(6) + '';
  }
  } 
  }
  var loca=document.location+"";
  var elements; 
  elements = document.getElementsByTagName("iframe"); 
    for (var i = 0; i < elements.length; i++) { 
    if(elements[i].src.indexOf('googlesyndication.com') > -1) 
    { 
    elements[i].onfocus = log;
    iFr=elements[i];
    }  
  }
  </script> 
  <?
  if (isset($_GET['site']) && isset($_GET['target'])){
    $cip=$_SERVER['REMOTE_ADDR'];
    $site=$_GET['site'];
    $target=$_GET['target'];
    putenv('TZ=US/Pacific');
    $mdate=date ("Y-m-d h:i:s");
    if($wpdb->get_var("show tables like '$table_name'") != $table_name) {
      //create table
      $sql="CREATE TABLE `".$table_name."` (
      `mdate` DATETIME NOT NULL ,
      `ip` VARCHAR( 15 ) NOT NULL ,
      `site` VARCHAR( 255 ) NOT NULL ,
      `target` VARCHAR( 255 ) NOT NULL ,
      PRIMARY KEY ( `mdate` )
      );
      ";
      require_once(ABSPATH . 'wp-admin/upgrade-functions.php');
          dbDelta($sql);      
    }
      //insert click
      $insert = "INSERT INTO ".$table_name.
                " (mdate,ip,site,target) ".
                "VALUES ('".$mdate."','".$cip."','".$site."','".$target."')";
            $results = $wpdb->query( $insert );
  }
}
Tags: programming, php
Rusty Wright 12/10/2006 23:06

It's one of those things where it's so prevalent and there are so many books and web sites about how to do things with it. And every isp provides it, along with that crap database, MySQL. Linux, Apache, MySQL, and PHP. And I suspect that a lot of the people doing php programming don't have much, if any, formal programming background. So they don't realize how ugly it is.

And on the flip side, let's face it, Java isn't easy to learn and get up to speed with. With Java it's not even clear to a beginner if you should do a J2EE app or a plain servlet app. People probably don't realize that there's an alternative, Spring. But even Spring has a nontrivial learning curve.

I confess that I feel the negative same way about Ruby and Rails; I want code that is compiled and whose type usage has been verified by the compiler, before I start the app or run any unit tests. I don't understand why anyone would want to use a system that's so loose.

Tufty 12/11/2006 01:11

I've seen good code and bad code. I pride myself on the clarity of my code, and I'm a PHP developer by nature and occupation. It's perfectly possible to write clean PHP with a minimum of confusion, but unfortunately the codebase I have to work with for my job hasn't been.

I frequently wish I could throw it all out and start over again, unfortunately it's a live system which is constantly in use. We're talking about a total rewrite, but that will come after the current version is feature-complete...

bla.st 12/11/2006 05:31

Sometimes having everything on one page makes life a whole lot easier. For example, consider what is on a typical login page:

  • A form with a username field, password field and a submit button made in HTML

  • Error messages if a user types invalid details

  • CSS or a table to layout the form

  • SQL to check the users details

  • PHP code to issue the SQL statement, and do something if the users details are correct or wrong

Why not stick it all on one page? In my latest app, the login page including all the above is just over 100 liberally spaced lines. I have includes for the header, footer, and a global stylesheet, but why complicate things further than that? Here it is in action:

http://bla.st/site/login/

If I want to change anything to do with the login, I know where to find it, whether it be layout, logic, or database query.

Lee 12/11/2006 06:36

I think generally, PHP coders are less disciplined, but that is no reflection at all on the limitations of the language. Look at something like CakePHP, which demonstrates proper separation of concerns, structured code, etc - it is entirely possible to create large and maintainable PHP applications. The sad fact is that most PHP cowboys don't bother.

The guy who commented above obviously has no concept of OO or code/resource reuse - which is pretty fundamental for a well structured codebase.

I started with PHP, then moved to Java. I can see the benefits of each, but I tend to now prefer Java. Having said that, when I'm writing psuedo code in my Java classes, it tends to be PHP :)

Each to there own, but don't start getting the wrong idea about a language from a bad example - try doing some proper investigation before jumping to conclusions.

pcdinh 12/11/2006 07:11

You dont like PHP because you dont know PHP enough. The ability of a language is very different from how you use it. Please have a look at CakePHP, SolarPHP and Zend Framework to understand why and how PHP Developer can seperate presentation layer and business layer. If you love iBatis and Hibernate, you also fall in love with phpdoctrine

Bill A. 12/11/2006 15:29

Thank you for taking the time to write a thought provoking article. You brought up many excellent and valid points on PHP and the Presentation Layer of Web Applications:

This is a common struggle across web application languages and tools. The key is in the beginning of your piece where you state:

“…MVC approach. Splitting up the application into logical sections or layers proved the only way to manage and maintain development of a serious web application”.

This is the key to while PHP is gaining favor for this writer.

HTML and CSS are strong tools for the presentation layer but always need some element of scripting if dynamic information is to be utilized. In the past I have found JSP/ASP to powerful but be very ridged and sometimes difficult to use. PHP provides the same functionality with much greater flexibly and options. However, per your MVC comment, the key is to only perform presentation layer logic in PHP. PHP is very powerful and can do much more as a server tool, but the key is to follow a MVC approach. PHP does support the use of Java Objects. Thus Business rules and data are performed in Java (Can use IBATIS, JBOSS, etc). PHP calls of the java objects of clean and scaling/performance of java can be leveraged.

These reasons are why this writer sees the appeal of PHP as a presentation layer tool and thus see the value and appeal of PHP. What are your thoughts on this view?

A PHP Coder 12/11/2006 15:39

The only thing in your article that makes any sense is the bit about seeing bad coding practices in various languages.

The rest is just pointless bashing.

Andrew 12/11/2006 15:47

I would say that the more you know about PHP the less you should like it (if you have used a better language anyhow). My favorite example is how references work (at least in 4, might have been fixed in 5 ?) where they were just a horrific hack into the parser and didnt make it properly into the language so there were lots of annoying edge cases where you just could use references or had to hack about, often with variable variables.

yuck. Python please.

Nick 12/11/2006 16:49

As an ASP.NET developer, I totally agree.

But, I think a distinction has to be made, seperation of logic and what not is only vital iff you're doing a large, scalable, enterprise-level application.

bla.st's point, while likely as naive as it sounds, isn't necessarily invalid if all you're doing is making a little web app. But, it quickly crumbles in an unmaintainable nightmare as soon as you need to:

  • scale across multiple web servers

  • scale across multiple database servers

  • maintain state between all those servers (ie: no sticky load balancing)

  • implement your application in more than one language

  • support multiple web server platforms (ie: IIS, Apache, etc)

  • support multiple DMBS (MSSQL, Oracle, etc)

Currently, I work on an ASP.NET application that has to do all of that, and the though of doing it in PHP makes me want to hang myself.

Christopher 12/11/2006 17:11

I think it is pretty funny to write an article about something that you admit you "Will Never Understand." It is not very interesting to read something by someone who knows very little about the subject ... ah well.

Maybe the title should have been:

"I Will Never Understand How Something Can Be Useful That

Does Not Do Things The Way I Think They Should Be Done!"

And I love the usual comment "I work in Language X that has everything I need, and the thought of working in Language Y makes me want to hang myself."

I would hope with all the great programming languages available today that the ranks of close-minded programmers would dwindle ... again ah well.

Paolo 12/11/2006 18:24

I totally agree with Christopher comment.

dreamscape 12/11/2006 18:34

>> In PHP there is no alternative to embedding everything together.

Are you some kind of moron?

>> Currently, I work on an ASP.NET application that has to do all of that, and the though of doing it in PHP makes me want to hang myself.

Please do. Really, we're all waiting.

raveman 12/11/2006 19:22

you also have MVC in PHP(there isnt embed MVC in J2EE until version 5). PHP can be also be OOP(just like JavaScript :D), so i think most people dont use it if they are not force into it ;). The reason why php can be ugly is because it doesnt have code standards, im j2ee developer but i also like php.

Paul 12/11/2006 21:05

I'm a Python programmer and generally not a huge PHP apologist, but you're putting up a straw man here. "This code sucks, this code is written in PHP. PHP sucks!" Actually, on a line-by-line basis, the code isn't so bad. The intermingling of presentation and logic that (rightfully) freaks you out is not a feature of PHP, except in that PHP doesn't disallow it. I'm sure there are lots of terrible embperl sites out there too.

There are plenty of people who practice, and advocate, better PHP coding, e.g. the kind of stuff I write about here: http://e-scribe.com/news/159

pcdinh 12/11/2006 22:51

@Nick

@support multiple DMBS (MSSQL, Oracle, etc)

When you work with PHP, there a lot of classes to help you work with different database servers.

Native PDO (PHP 5.1): single interface for a lot of major database servers

PHP libs: MDB2, PEAR::DB, PHPDoctrine, Creole

@support multiple web server platforms (ie: IIS, Apache, etc)

Please read PHP Manual carefully. PHP is very portable. In this perpective, ASP.NET is a truly nightmare.

@maintain state between all those servers (ie: no sticky load balancing)

Have you tried any distributed session engine in PHP? However, one thing should be recalled: PHP embrace a share-nothing architecture and so, PHP application is more scalable with ease than JSP/Servlet/EJB... and of course, ASP.NET when APC is enabled.

@scale across multiple web servers

@scale across multiple database servers

Are you sure that this task is a PHP's responsibility? Database clustering, replication and NFS do it all. Please have a look at Friendster, YouTube, Digg and MediaWiki. They are all implemented in PHP. Never heard a about big ASP.NET application.

@implement your application in more than one language

You are totally wrong. Have you tried Java-PHP-Bridge extension?

There are a lot of misleading thoughts on PHP due to its very successfully history. However, history is evolving. Many hardcore PHP Developers have joined in big projects like CakePHP, SolarPHP, Zend Framework, Symfony to promote best practices in PHP programming: design patterns, OOP, coding standard, coding best pratices. With those projects, I see no gap between the beauty of Object Oriented Methodology and PHP programming. I am a Java developer (in my company) and PHP Developer (im my PHPVietnam group) and I understand that Java and PHP can work well together to develop elegant applications. For instance: SAM extension has bridged the gap between PHP and Java Messaging Bus.

pcdinh 12/11/2006 22:57

Could you please delete my duplicated post?

It is more convenient if the Save button is disabled after being pressed ;)

notrigger 12/12/2006 01:45

PHP OOP is possible in all regard. And clean PHP can come from this. I do think that it does take more time in PHP. But PHP was written from a procedual and some may consider (as i've heard) functional (but they're idiots and don't know what haskell, lisp and F# could possibly do to be productive). Either way, I think the main problem is web programming isn't as much OO as people think it can or should be.

It's difficult to think of the user actions as being OO calls and not procedural without the language sucking your left nipple (asp.net w/ C#), but PHP can have a nice OOP design whilst being something that isn't compiled into a mess of cryptic lines that Robert DiNero at the end of 'cape fear' would be confused about.

PHP can create a nice CMS with modules that are easily installed and secure, perfect for web sites. It can create this site with an ease and expandibility (polls, files, news...) that can be organized to the user, with a smart, educated developer outlook .

I challenge you to look into OOPHP and see how it fails short on others... It can be done.

Matt 12/12/2006 01:46

just because you CAN do something doesn't mean you SHOULD. php is designed to be both simple and powerful. if you do a 5 or 10 line script, you can easily include a bit of html and javascript into it. if you have a 5000 line project, it would be smart to use some kind of template system and have very minimal html in your php files. as with many other area's of computing, if you give people power, it will most likely be abused. it's pretty easy to jump right into php and start programming, but it's much more difficult to be truely good at it and write clean manageable code.

Chawlie 12/12/2006 02:51

I am a C#, C , VB, PHP Developer. and it all works with dot-net, yay. php can be a great language, it only sucks for most people who use free code for dumb shit like CMS Systems written by 14 year olds who have no Idea about business logic. Is PHP good? Yes. Is .Net good? Yes. and Java too im sure. but the intelligence is within the programmer not the language, for the most part.

flash 12/12/2006 07:35

I agree with pcdinh. While I think PHP has many, many problems (and I am someone who uses it on a daily basis at work), inability to separate the various components of an application. There are several quite mature frameworks to assist in this very task.

'I bet the ultimate PHP coder can do a careful job of creating good code, but the problem is that the average coder is highly unlikely to due to the language itself.'

The average code is able to shoot themselves in the foot regardless of language, this only changes through experience. Choice of language may have some impact but it's minimal in my opinion compared to other factors.

flash 12/12/2006 07:36

If I could read and write properly I would have said 'inability to separate the various components of an application is not one of them'...

phpcoder 12/12/2006 08:45

PHP is good, i love it, I know ASP, java, .net, but i love PHP most!

codist 12/12/2006 09:44

I love all the comments, and will write a followup.

Mohamed BADR 12/12/2006 09:45

well i have been working with PHP and ASP.NET and i find that PHP is way more better than ASP, one thing that is making it dominate is that the open source concept and lots of free applications written in PHP so new developers can learn it and use it everyday, on the contratry in microsoft technology it's always kept secret lot of tools but learn it on your own , it's more near to impossible

Shafiq Rehman 12/12/2006 11:20

PHP is too logical for my brain :)

Deane 12/12/2006 13:03

This is such an unbelievably tired argument. Seriously, did you put 10 seconds worth of thought into writing this? This entire diatribe is dripping with laziness, to the point where I don't even know where to start picking it apart.

Congratulations in breaking new ground in unoriginality. The answer to every question you posed in this essay is a Google query away, had you taken the time.

Even just commenting on this steaming pile of crap makes me want to go take a long shower.

PHP Coder 12/12/2006 13:22

I suspect you love the attention more than the comments.

I've got to give you points on attention-whoring, that's for sure.

Shaggy 12/12/2006 16:13

In response to Rusty's comment - pfffftt I've plenty of formal training/commercial experience (JAVA and C ) and I love PHP, like any language PHP open to abuse, done correctly its very elegant and as efficient as any pre-compiled language.

Compiled languages have their place and offer great resilience especially for back end systems - but, dynamically compiled languages such as PHP offer rapid development, easy integration and most importantly (from a business POV) faster route to market. It does have drawbacks, but the commercial benefit far outweigh these.

Genius 12/12/2006 16:37

Lol you are really a joke. Should i take a secretary that writes a java application? And later judge the results?

First learn "how" to do the things in php and dont just use the easy ways that encourage beginners to start with php.

Use a template language, use php5 oop, select a framework (like you do in java) and then try gain your FUD.

Guna 12/12/2006 18:27

Hi,

It is not the programming language which is responsible for bad coding style. It is the programmer who writes bad coding. Anybody disagree with this point of view?. Experienced programmer can write quality code provided maintaining different layers in any programming language. Moreover it is the architect who is responsible for software design/framework and architecture. See the coding standard of Joomla, xoops, drupal. Their layer seperation(MVC) is the best example.

Java developer 12/13/2006 07:41

I have done web-development with PHP and I think it's a nice tool for some simple purposes.

In our company we mostly do things with Java. Many have a background with Java, Cobol, VB or C . There are a few programmers who like PHP and all "free" stuff ("LAMP"). Unfortunately, they are also the persons who tend to not follow our architectural guidelines, their code is messy and hard to understand, they don't re-use, they don't comment.

Thus, my real world experience shows to me that PHP somehow tends to lead to bad design and people most fond of PHP tend to do bad design.

David 12/13/2006 09:33

First off all these PHP bashing comments are from tards. With any language you are bound to find code which is untidy and inefficient, that is solely the fault of the programmer and not the language. To me it sounds more like the old addage "a good workman never blames his tools" or "a good programmer never blames the language".

PHP is an easy to learn and powerful language the fact that you haven't even bothered to actually learn the language but rather looked at some you pulled from the web makes your comments completely laughable. It would be like me bashing HTML because there are so many examples where the code is programmed sloppily.

I wholeheartedly agree with Christopher, pcdinh and Chawlie on this.

And Rusty MySQL is a crap database? LOL let me guess you prefer MsSQL.

nodia 12/13/2006 09:40

To Java developer

You are too bad to be a developer. A smart developer would never think about a programming language as if it was such a drug.

You wrote: they are also the persons who tend to not follow our architectural guidelines

==> Does it mean that your architecture sucks?

You wrote: their code is messy and hard to understand

Huh, PHP code is very simple to read. However, every developer needs a bright mind

You wrote: they don't re-use

For what? Code re-using is not the purpose of software projects. Have you ever cared about: memory footprint, loading speed, line of code, development speed, ease of deployment and maintenance...

David 12/14/2006 10:51

This line by the way is complete nonsense,

"Unfortunately with PHP (among others) it's usually beyond the developers to write easily maintainable applications as the language simply doesn't allow it."

It is extremely easy to write a structured program in PHP by using require(), Include() and their sister statements (require_once etc). Many times I will build one php class in one document to handle the template engine, one php class to handle database connections one php file containing all of my general functions and then a page for each area of my project for example, adding a record, editing a record, reporting etc.

And it is also in this manner that I can re-use code numerous times over without having to write it in several different places.

Jemm 12/14/2006 12:19

@pcdinh

"Never heard a about big ASP.NET application."

Have you heard about MySpace?

http://weblogs.asp.net/scottgu/archive/2006/03/25/441074.aspx

Giz 12/16/2006 02:59

This lazy article uses the same ill conceived arguments that frankly has been attempted and debunked many times before, by people who actually managed to at least formulate an argument, unlike yourself. I'm surprised you didn't bring up "register_globals" as an example of why PHP is bad, but then, you admitted that you don't know much about PHP at the start of the article, and you probably should have stopped there.

I guess all the idiots behind sites like Youtube, Digg and Wikipedia, or companies like Yahoo and Google must be scrambling to absorb the wisdom you've provided here. I guess when they chose PHP it was simply because they'd never heard of Java.

TP 12/16/2006 09:43

The problem with writing opinion pieces is that it usually reveals more about the writer than the subject. In the case of the.codist, I'd say that this is absolutely true.

I've been programming since about 1973 and I regard PHP as a highly adaptable tool. It's pretty easy to make a mess (nothing compared to Perl, by the way) and, with a little thought, you can separate all the essential layers wrapped in tidy objects that are completely comprehensible. I've lived through the advent of numerous programming paradigms, many of which became embedded in new languages. The simple truth is that it's not the tool but the craftsperson that determines the outcome.

Try thinking about what people have to deal with - how projects get started, who has what resources to work with. It's very clear to me that a relative novice with no money and simple machinery would have to be insane to consider starting up with a framework like Java. Not that Java is inherently bad, although it is very complex to run even rudimentary experiments for novices. PHP has so much to offer all skill levels that, by rights, it should be as popular as it is.

BTW, I noticed that one of the comments (above) bashes the whole LAMP world. It's a sad commentary when people cannot see simple virtue when it's staring right at them. You folks who think only garbage is free have a lot to learn about planet earth.