What I Like About PHP
coding.simon.geek.nz
coding.simon.geek.nz
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. 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.It's really that simple.
At least there is Moonscript to save it...
"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."
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 initialisationOn 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}" :)
I just run `coffee -wc .` on my source directory and pretend I'm using JavaScript everywhere else.
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...
Yeah, that's not the reason why people complain about it.
Worth reading once, if you keep wondering why everyone is slagging off the language you love (and that language is PHP).
[1] not yet in this thread, but at least once each in a thousand other HN PHP threads
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.
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.I think that would be called strong typing (as opposed to type enforcement).
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).
... 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 givenI mean, it's certainly extensive, but it's rife with the worst programming practices, and extremely bad/unsafe examples.
The best thing are the comments in the docs of people telling you how wrong the docs are.
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?
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 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).
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.
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.
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.
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.
If it's not unusually flexible, why extol its flexibility?
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.
To build an extra robust tool you need a lot of planning, and a lot of factors are considered during the planning.
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.
Python's prolly similar.
I can not interpret this in any way where a reasonable person would consider it accurate. What exactly do you mean?
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.
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.
Same goes for Python, then.
>Blub paradox doesn't apply.
You did describe yourself as a "PHP Guy".
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.
A perfect metaphor for me reading this thread: https://i.imgur.com/fKX2Xoh.png
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 libraries and improvements to the language follow from its popularity, which followed from its simplicity and usefulness.
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.
And for most small projects (which are most of them, really) you don't need to do it in production, either.
Why would you choose something kinda grimy when you don't have to?
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.
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.
Some more than others.
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