Hacker Timesnew | past | comments | ask | show | jobs | submitlogin
What I Like About PHP (simon.geek.nz)
45 points by simon_w on Dec 10, 2014 | hide | past | favorite | 87 comments


I'm a programming language geek, a code lover and a syntax fanatic. And there are a ton of things I love about php:

    class Animal // yeah! real classes!
    {
      function hello($name="nobody") // nice default variables
      {
       echo "hi $name"; // sexy variable expansion!
      }
    }

    class Dog extends Animal // logical syntax :)
    {
     ...
    }

    function f()
    {
     $x=123; // variables are local by default and need no initialisation
    }
I could go on for a long time, listing all the language constructs I like in PHP. All other languages I tried have quirks that annoy me.


Remarking on the fact that variables are local by default makes me wonder exactly how many programming languages you're familiar with. That's an extremely low bar, not really something to love.


Low bar or not, if you do anything web-facing, there is no way around javascript. And you will do a lot of stuff in a language that makes variables global by default.


A car metaphor for this conversation:

"I love my skoda! It has four wheels, and a roof, and a passenger seat!"

"That's a pretty low bar for things to love about a car. Pretty much all other cars also have those features, and they do them better."

"Yeah, well I also ride a bicycle, and my bicycle doesn't have those features."


Conversely, there's a long list of languages where variables would not be local by default


Insofar as there is a ridiculously long list of languages nobody has ever heard of, I guess this is true. But it's not true if you're comparing it to languages that are actually used in modern programming. Even if you're considering languages as obscure as, say, Standard ML, you'll still not find many that have a default global scope for variables inside functions. There's pretty much JavaScript, Perl, Fortran and Cobol. I can't think of any others that are even worth mentioning nowadays.


Lua.

At least there is Moonscript to save it...


I'm a programming language geek, a code lover and a syntax fanatic. And there are a ton of things I love about coffee-script:

    class Animal # yeah! real classes!
      hello: (name="nobody") -> # nice default variables
       console.log "hi #{name}" # sexy variable expansion!

    class Dog extends Animal # logical syntax :)
     ...

    f = ->
     x=123 # variables are local by default and need no initialisation


CoffeeScript is interesting. So far I did not experiment with it too much. So I'm not sure if I would like to do work in it.

On one hand, it looks nicely terse. On the other hand it looks a bit cryptic.

The thing that stops me from trying it for a project is not the language, but the available environments. Having an additional compliation step adds complexity to the system and the workflow.

One thing I cannot resist to say is that to me "hello $name" is sexier then "hello #{name}" :)


Well sure, but you can put arbitrary expressions in the #{} syntax. PHP has a similar syntax for that.

I just run `coffee -wc .` on my source directory and pretend I'm using JavaScript everywhere else.


`f` in your example is a global function that cannot be redefined.


Don't like global functions? Don't use them.

It's really that simple.


Which is a good thing. When you have ...

    function f($x) { return $x*$x; }
...in your code, you know that you can always call f() to get the square of something. Hallelujah. Functions as they are meant to be.


You're joking, right?!


> nice default variables

If you think that's nice, I'm about to show you something which will BLOW YOUR MIND :D

    >>> def hello(name="anybody", age=10):
    ...     print "hello %(name)s, aged %(age)d" % locals()
    ...
    >>> hello(age=42)
    "hello anybody, aged 42"
But wait, there's more!

> yeah! real classes!

You think PHP's classes are real? Just wait until shit gets REAL real when you subclass a primitive!

    >>> class ExtremeInt(int):
    ...     def __new__(cls, val):
    ...         return super(ExtremeInt, cls).__new__(cls, val)
    ...     def __add__(self, other):
    ...         return (self * other)  # Multiplication is EXTREME! addition
    ... 
    >>> 
    >>> x = ExtremeInt(42)
    >>> print x + 2
    84
Dare I stop there? I dare not!

> sexy variable expansion!

You think formatting strings based on local variables is sexy? Sure, we can do that:

    >>> name = "bob"
    >>> print "hello %(name)s" % locals()
    hello bob
But why not format a floating point number to a set number of decimal places based on a dictionary?

    >>> things_to_template = {"pi": 3.14159}
    >>> print "My pi is %(pi).2f" % things_to_template
    My pi is 3.14
What about formatting based on an object's attributes?

    >>> class Animal():  # HOLY SHIT REAL CLASSES!!!!
    ...     def __init__(self, name):
    ...         self.name = name
    ... 
    >>> my_ferret = Animal("Mr Awesome")
    >>> print "My ferret's name is %(name)s" % my_ferret.__dict__
    My ferret's name is Mr Awesome
Is that the end? It's 4am here and I'm barely conscious, but no!

> logical syntax [for single inheritance] :)

Ready to have your mind blown FOR A SECOND TIME?!?!?

    >>> class Animal:  # SUCH CLASS.
    ...     def __init__(self, spec):
    ...         self.spec = spec
    ... 
    >>> class Awesome:  # SO REAL. WOW.
    ...     def __init__(self, awesomeness):
    ...         self.awesomeness = awesomeness
    ...
    >>> class Ferret(Animal, Awesome):  # Logical syntax for MULTIPLE INHERITANCE OMGOMGOMG
    ...     def __init__(self, awesomeness):                                        
    ...         Animal.__init__(self, "Ferret")                                     
    ...         Awesome.__init__(self, awesomeness)                                 
    ... 
    >>> mr_awesome = Ferret(9001)
    >>> print "Mr Awesome is a %(spec)s and his awesomeness is %(awesomeness)s" % mr_awesome.__dict__
    Mr Awesome is a Ferret and his awesomeness is 9001
And that final part?

> Variables are local by default

...

...

Actually I can't think of a way to improve on that. It's like saying "I love this language for being turing complete". Sure, that's a good thing. The best thing, perhaps. But you sound kind of weird when you list it as a particular high-point of a language...


> It appears that just because PHP has been used a lot more than most languages it gets compared to, its warts are known about a lot more which makes it a much easier target.

Yeah, that's not the reason why people complain about it.


Then why do people complain about it in your opinion? Shouldn't leave the conversation hanging ;-)


There's no need to continue a conversation that's been had a thousand times already.


I haven't seen the obligatory fractal link yet!


sigh http://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/

Worth reading once, if you keep wondering why everyone is slagging off the language you love (and that language is PHP).


http://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/ (it's actually a pretty decent article, anti-PHP or not.)


I've started using this to measure the quality of a PHP thread. When a thread reaches 3 Fractals you may as well bail.


You wait that long? I go into them knowing from the start that the whole thread will be divided into "PHP is terrible", "PHP is terrible but it gets the job done", and "PHP is my second language (after javascript) and I think it's great" camps - no particularly useful discussion will occur from the first two camps, but we can at least draw some positive value from the thread by enlightening the third group (or laughing at them, depending on how stubborn they are).


It usually doesn't take very long. It's like a compulsion for some people.


It's the Godwin's Law of PHP discussions.


Not much of a conversation when someone says "That's not why..." and then they don't expand on it.


Obligatory standard explanation, which has been linked a thousand times already[1]: http://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/

[1] not yet in this thread, but at least once each in a thousand other HN PHP threads


The number one reason PHP is liked and adopted so much for the web is there is no state. Each and every request starts fresh, which reduces a lot of complexity and the barrier to entry. Also, the fact that it is in itself a templating engine, makes it faster to produce apps.


Oddly, it was that realization -- more than all the other many nits people pick with PHP -- that started making me want to claw my eyes out when I thought about PHP.

PHP has come a long way in many respects, but it's still fundamentally wedded to a 1999, CGI-ish model of the web: pages are fundamentally static entities that you add dynamic bits to as needed. It's a "template engine" because it's basically designed to embed scripts that we would have previously stuck in /cgi-bin right in your web pages. In that world, PHP was pretty awesome.

But in a world of MVC frameworks, "every request starts fresh" means that on every request, the entire framework starts from scratch. It loads libraries and configuration files and ORMs and controller routing on startup -- and it has to do it every single time. Yes, I know things can be and are cached, precompiled, lazily loaded, etc., but that can't completely overcome that. From what I've gathered over the years, PHP is a pretty fast language -- but PHP frameworks consistently get their asses kicked in benchmarks, and I can't help but suspect there's a correlation.


Rails consistently under performs Django, and both under perform HHVM, go, Java, and C++ frameworks. Benchmarks don't seem to be as important as the perceived social status of a language.


I think it's a self-enforcing trope, though, these days. Everyone uses PHP because every host has PHP. Every host has PHP because everyone uses PHP.


Most people complaining about PHP haven't actually used it in an enterprise environment.

Using JetBrain's PhpStorm with a proper framework is simply not the PHP of 10 years ago.

One of my favorite features is type enforcement; consider the following code:

  class User {
    function is(\Auth\Role $role) {}
  }
If something other than an Auth\Role object is passed in, a runtime exception occurs. Better yet, PhpStorm will check the types in real-time and underline type errors immediately.


>If something other than an Auth\Role object is passed in, a runtime exception occurs.

This is not impressive. Even most popular super-weakly-typed languages support runtime exceptions for type errors.

>Better yet, PhpStorm will check the types in real-time and underline type errors immediately.

This feature is frequently called "static typing". Many languages have this (and not just as some IDE extension).


> One of my favorite features is type enforcement

... that's a feature that pretty much every other language either already has (and does better), or explicitly does something different (but better) :S

Specifically, every other langage that I know of with type checking support has type checking for classes and primitives. PHP, not so much:

    function test(integer $z) {
        print $z + 1;
    }
    test(42);
    
    PHP Catchable fatal error:  Argument 1 passed to test()
    must be an instance of integer, integer given


> If something other than an Auth\Role object is passed in, a runtime exception occurs.

I think that would be called strong typing (as opposed to type enforcement).


I think they called it type checking when it was introduced, I would wager to avoid it being confused with strong typing because in PHP you cannot typecheck primitives (as of 5.6)


Wait, wait, the PHP documentation is GOOD? Wat?

I mean, it's certainly extensive, but it's rife with the worst programming practices, and extremely bad/unsafe examples.


Although I think that PHP is certainly not the best language in the world and it's pretty easy to write unsafe code in it, I don't think that's true.

I agree that PHP tends to trick you into writing unsafe code, but I generally don't agree that their documentation is full of unsafe examples (not anymore at least).

Can you name an example that proofs your point?


lol, yes.

The best thing are the comments in the docs of people telling you how wrong the docs are.


No seriously, that is actually one of the best things. The comments on PHP docs are far more informative than the actual documentation for many other languages. Most everywhere else the caveats are simply left up to the developer to discover the hard way.


They saved my ass plenty of times, but I wouldn't count them to the quality of the docs.


I personally don't think PHP is that bad of a language either. I mean all languages have caveats, there is no such thing as a perfect language. I think PHP gets a bad rep because there is a lot of bad code out there and people blame the language for the bad code, which is like blaming car manufacturers for drunk drivers. But some of the criticism is legitimate and we would all be very naive regardless of our stance to not at least admit that PHP has some design issues.

The biggest issue I have always personally had with PHP is parameter consistency. A few might laugh and think this is a pretty small thing compared to other issues that PHP has, I agree, but it is annoying nonetheless. Some inbuilt methods want the needle first, others want the haystack first. Array functions tend to prefer needle first then haystack, string functions tend to prefer haystack first then needle.

The problem is PHP is a culmination of years upon years worth of backwards compatibility. The quirks around the order of parameters on inbuilt methods will probably never be addressed, it is something we just have to deal with. There are other quirks I won't bother detailing, but I still like the language. However I do acknowledge that parts of the language are a series of hacks. While PHP is not a perfect language, it works. And we also have to acknowledge not too long ago, Javascript was a pretty horrid language with a tonne of quirks to work around as well and will continue to be until we can support great ES6 features without polyfills.

I won't pretend to be a code elitist. I use whatever gets the job done. When a client has a limited budget of $2000 and wants a new website they can manage themselves, nothing beats Wordpress and Wordpress is built on PHP. No other language has a CMS that rivals the power of Wordpress (trust me, I have looked as well). I would argue many people that still use PHP are using it solely because of Wordpress.

Not to mention PHP just works out-of-the-box with almost every hosting provider on the planet with minimal configuration (if any) and can easily be tweaked for great performance (caching and compilation). I still think that PHP has a future ahead of it. It seems there are efforts underway to make it better, Facebook have contributed greatly to the language especially. We might one day see something like ECMAScript 6 happen for PHP where some of the biggest complaints are addressed (who knows).


> I think PHP gets a bad rep because there is a lot of bad code out there and people blame the language for the bad code

Where do you get the idea that people judge a language based on other people's code in it, and not on their own experience of using it? My experience is quite the opposite -- I can't remember the last time I looked at anybody else's PHP code, my hatred of it comes entirely from using it myself, and comparing it to other languages which I've also used myself.


> I think PHP gets a bad rep because there is a lot of bad code out there and people blame the language for the bad code

I think in 5-10 years, in a post "everyone should learn to code" world, people will say some of the same things about Node.js or Rails that have been said about PHP for the last decade.

Beginners are going to make mistakes, and PHP was appealing to novice programmers (for a lot of the reasons listed in the article).


>people will say some of the same things about Node.js or Rails that have been said about PHP for the last decade.

Really? Please tell me which of these things: http://webonastick.com/php.html applies to ruby. People have been complaining about javascript being shitty for just as long as javascript has existed.


I don't know enough about Ruby to make any specific criticisms of the language. I just know that Ruby/Rails is being recommend to beginners (through Code Academy). I guess I could have said Python instead, but I don't think Python's web frameworks (Django, Flask, etc) have the market share that Rails does.


So, you have no basis to support your claim, and admit you do not have the understanding required to make such a claim. Then why did you make it?


I never said people would criticize Ruby because of the language itself. I said that it could POSSIBLY (note that this is pure speculation) get the same stigma as PHP because it draws in a lot of beginners.


And my point was that PHP does not get stigma because it attracts beginners. It gets valid criticism because it is horribly broken. That's why I showed you one of the many sites making those criticisms.


> I think PHP gets a bad rep because there is a lot of bad code out there and people blame the language for the bad code, which is like blaming car manufacturers for drunk drivers.

This a thousand times, and it's not just PHP, but every mainstream language (like people blaming C just for the sake of blaming C).

Languages are tools, and they should be used when they make sense, you are not going to use C to build a website, and you are not going to use PHP to write a firmware.


It's still serving 82% of websites, and it runs some of the largest and most successful properties. It's flexible as all get out, and powerful whether you're running a site or just some command line scripts. I don't do too much with it these days (besides the Parse and Facebook PHP SDKs) but I'll always defend it.


>It's still serving 82% of websites

Popularity =/= quality.

>It's flexible as all get out

As opposed to what? Lots of modern languages have extensive web support and can have libraries for most common tasks.


It doesn't have to be in opposition to anything. There are lots of languages, use whatever one you like that is acceptable for your situation.


>It doesn't have to be in opposition to anything.

If it's not unusually flexible, why extol its flexibility?


What language is php flexible compared to? If anything it seems inflexible.


I truly don't understand this constant crying about programming languages that our community participates in. Seriously. Great frameworks and libraries out there exist and hide most of the cruft you deal with.

I write absurd amount of code and I truly do not start crying because I'm using PHP, JS, or something else. I run into style issues, for instance, in PHP I might use is_num instead of typeof foo === "integer" like in javascript.

When I have a problem with a tool I'm using, it's more like "Arg, the API for new modules in angular is too close to the API for calling already created modules!!" not, "Oh no, jQuery is bad because Backbone is bad, because backbone is written in JavaScript, and you can do some mighty awful things in JavaScript!"

If you're crying about things on the language level, you're not building robust systems.


I don't know. Just today I was crying because I can't pass an object property to a function with proper scoping and that I can't pass an instance method as a closure. These are interpreter deficiencies brought about by weak programmers writing a programming language.

Both of these things can be rectified by some gymnastics or call_user_func_array (very slow), but it's something that I could do in JavaScript or C# or almost any other language if I wanted to, but not PHP.

It drives me crazy, and almost every day there are one of these things. I never have to say "I wish JavaScript did $x," unless there's a library I need that I don't have. On the other hand, in PHP there has never been a time that I've had to say "Oh, there's no library for this."

It's a game of tradeoffs, and, for me, bitching about syntax is greatly preferable to having to port a library to another language or start from scratch.


...or you are trying to build extra robust systems. And to do that, it helps to choose carefully which libraries to use because one has to understand them all. And then readability of the language is becomes an issue and I'd argue that average readability varies between programming languages.


You don't say "I'm going to build an extra robust tool, let's start <?php class ExtraRobustTool { ... }"

To build an extra robust tool you need a lot of planning, and a lot of factors are considered during the planning.


PHP guy here. Which doesn't mean that I love php that much, but still pays all the bills. How I ended up doing PHP? Long story. Anyway, i've been working in almost any kind of environment. PHP powers massive and remarkable architectures and i NEVER felt it was falling short during implementations. Another story is the community, which is also the only damn community which has scientists and amateurs sitting in the same room. The quality of the code depends entirely on the person who is using the language, still I think that actually allowing "non-programmers" to power their projects easily (despite being badly designed, they still can fly) with PHP is a feature and not a bug.


>i NEVER felt it was falling short during implementations.

http://c2.com/cgi/wiki?BlubParadox

>the only damn community which has scientists and amateurs sitting in the same room

I see scientists of all sorts in #python and #r, and scientists of the more theoretical sort in #haskell quite frequently.


As far as i can see, smart people of HN is failing to grasp the meaning of a simple sentence.

You won't see ANY amateur using R. Period. In the PHP community you find people building hairdressers websites and distributed systems experts. It's not about having scientists or having amateurs, is about having them together, at the same time and in the same room.

As a side note: Blub paradox doesn't apply.


>In the PHP community you find people building hairdressers websites and distributed systems experts.

Same goes for Python, then.

>Blub paradox doesn't apply.

You did describe yourself as a "PHP Guy".


>You won't see ANY amateur using R. Period

What? I see tons of them. I am one of them. What kind of ridiculous assertion is that?

>It's not about having scientists or having amateurs, is about having them together, at the same time and in the same room.

It is about you pretending something is unique when it applies to every single programming language in existence.


Just invoking BlubParadox seems condescending.


>only damn community which has scientists and amateurs sitting in the same room

Python's prolly similar.


Be elastic, the core concept is not about "being unique".


Than why did you qualify it with "only"?


>which is also the only damn community which has scientists and amateurs sitting in the same room

I can not interpret this in any way where a reasonable person would consider it accurate. What exactly do you mean?


I agree for the most part. There are a few infuriating things, especially coming from a more functional background, that drive me crazy. People who shit on PHP aren't being objective.


My mind is honestly blown by people here thinking that half-assed type checking, local variables, and classes are novel and unique features of PHP which make it better than most other languages. Am I really living in a world where people try PHP, and try Javascript, and consider themselves well-informed expert programmers who have seen all there is to see? :S

A perfect metaphor for me reading this thread: https://i.imgur.com/fKX2Xoh.png


PHP is a good language for solo devs that need to get shit done quickly. PDO is fast and stays out of the way.


I think one of the fundamental points that a lot of criticism of PHP misses (and there is a lot to criticize about PHP) is that it doesn't have to be a very good language to do what it needs to do, which is, almost entirely, CRUD.

Everything else aside, being able to get an iterable array from a database and crap out an HTML page with very little effort says a lot about its popularity. You don't need to be a good language to accomplish that, or even really a sane one. You can mix css, javascript and data sets together right in the same document. Insane? Probably. A bad idea? Almost always. But also weirdly liberating, and very easy to get from point A to B.


The brilliant thing about PHP is webapages as templates. It's so simple and easy to get something useful going, both to write it and deploy. Templates weren't new - shell had string interpolation - just simple and useful.

The libraries and improvements to the language follow from its popularity, which followed from its simplicity and usefulness.


What I like about PHP: ease of deployment. No builds or process restarts required. This makes it easy to prototype and rapidly iterate.


Well that isn't necessarily true. If you're deploying new code then you need to update the web server to point a new directory then that process needs restarting (or at least soft-restarting).

If you're redeploying into the same directory then you should be at the very least clearing the opcache so that old code lingering around in memory isn't served up.


Not really. My point is you don't need to do any of that during development.

And for most small projects (which are most of them, really) you don't need to do it in production, either.


The only thing I agree with here is that it is indeed easy to get started with PHP. It's also easy to get started with BASIC. You should not be using either to write a serious application in 2014.


I think PHP is lackluster, inconsistent, and feels pretty clumsy in general, but to suggest that it doesn't qualify as a candidate for serious application development in 2014 is a notion that arises from ignorance of the platform. Client requirements notwithstanding, it wouldn't be my first choice, but I've worked on very well engineered PHP solutions that were successful and have so far proven to be quite maintainable.

A strong engineering lead is very important (someone needs to enforce the use of composer, adherence to the appropriate PSR standards, testing, modern mvc/routing etc), but PHP is absolutely capable of producing fast, clean, maintainable software.


It can be a candidate, but when there are so many better candidates out there why bother? The only times I can understand it are for legacy reasons or if your developers only know PHP.


Perhaps your engineering team favors the workflow of a particular PHP framework.

Perhaps you've estimated that for a particular project, it might be worthwhile to leverage the talent and effort that's been poured into HHVM.

Perhaps you've had continued success solving a certain type of problem with a particular PHP library or tool.

Perhaps you are constrained by regional availability.

Perhaps you're interested in building a product or tool that you intend for your customers to deploy themselves and you want to provide them with the simplest path to accomplish that goal.

Perhaps you're building a complex SPA or an otherwise JS heavy application that only requires a simple back-end, and you want to focus your big bucks on attracting quality JS engineers while choosing cheaper PHP engineers for the relatively simple CRUD API component.


Why exactly? Why shouldn't you use PHP in 2014?


As an author of a PHP app, it's because there are better languages with better defaults out there. I don't understand why you would use a language with clunky libraries and hacked modules when you could use python, ruby, or node (amongst other great choices).

Why would you choose something kinda grimy when you don't have to?


Because there are nicer, faster and more sturdy languages available. Ruby, Python, Go, and JavaScript, to name a few. The age-old "PHP is so easy to deploy!!1" rhetoric doesn't really hold true anymore when it basically refers to shitty, oversold shared hosting. PaaS offerings like Heroku make virtually ANY language stupidly simple and cheap to deploy these days.


This isn't radical. PHP apologism is incredibly widespread. And it almost always takes the same poor form you chose here, of pretending everyone is just conflating preference with quality. No, supporting octal constants only by accident, and doing so incorrectly because it was an accident is not a valid design decision and simply a difference of opinion. Plenty of other languages have been used as much or more than PHP, without the same level of criticism. Consider the very real possibility that some of that criticism is valid and try reading it instead of dismissing it.


> Sure, PHP has its warts — every language does.

Some more than others.


I happen to agree, so bring on the downvotes

Some of the PHP criticism is valid, and most of it is valid if we're talking about pre-composer PHP. But with composer, namespaces and traits, PHP can be a lot of fun. Sure, there's no real concurrency support, but so far I'm able to live with that. It's also weakly typed, but there's a LOT of web apps that don't need strong typing. The documentation is a good starting point, but some of the warts will come out in edge cases. The only thing I'm mad about is needle/haystack. I also wish string and array slicing were as easy as they are in python




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: