Hacker News new | past | comments | ask | show | jobs | submit login
PHP: The Right Way (phptherightway.com)
393 points by bencevans on July 7, 2012 | hide | past | favorite | 219 comments

Straight, simple and to the point. Nice.

Missing test and QA tools though. Probably an oversight, since the author does suggest following Derick Rethans and Sebastian Bergmann.

And another one: read up on the SPL library before you start re-inventing that wheel.

All good points. If you'd like to submit a pull request, I'll be happy to credit you with the additions and get them added to the site.

This is a great idea. Quick grammar correction under Introduction>Input Filtering: remove the apostrophe from "That lead's to dark and dangerous places."

I like the general idea of this, but think that it is nearly useless in its current form. It's way too superficial. To teach newbies how to do things right it doesn't suffice to link to a few resources and hope that they'll read them (hint: they won't). Instead one needs more concrete code examples, etc. Which would obviously be too much for one page :)

As someone who taught themselves enough PHP to get by over the last 7-8 years, this is brilliant. I don't spend every day keeping up with the latest developments in PHP, but I know in that time the techniques I'm using must be out of date.

I've learnt JQuery and Python lately, but my Swiss army knife is still PHP. So this has already fixed a lot of incorrect techniques I've been suing in a side project.

I agree. It's very much in a v1.0 form right now. Once I move over to GitHub Pages, I hope to add more links to tutorials and code samples without bloating the document itself.

I think it offers a great starting point, though, and even though I've worked in PHP for a few years, I filled in a couple gaps in my knowledge. Thanks very much.

If you have ideas, the author points out that he's accepting contributions from the community: https://github.com/codeguy/php-the-right-way

PHP with these guidelines looks like JAVA to me, but without the relatively sane foundations.

It is fun how much a very old moralist sentence by Confucius applies well to PHP. He said 其本亂而末治者否矣 which can be translated, in software language development context, as "Build a nice, reliable language on shitty definition? Bullshit!".

(The word-by-word translation is "your - root - messy - and/but - leaves/result - governed/orderly - have ? not - hey!")

This sentence also resonates with the odd Turkish encoding PHPbug recently reported here: if you have so many wrong architecture decisions in the core of your product, no amount of patching and "under the rub" filling will save you.

Edit: added word-by-word translation + typo fixes.

This illustrates very common problem with people trying to criticize PHP.

First you demand some "foundations". But if you look on virtually all existing popular languages, none of them were designed exactly in the form they are now. Java had tons of changes and additions, Python had object model change and now has new version that changed so much that it's not even backwards compatible, etc. etc. Does it mean they lacked "sane foundations"? No, it means requirements changed, so did they. PHP changes too. You want formal definition of PHP? But what would be the benefit of it? Who would benefit from it existence? Without answering these questions it is hard to expect anybody would create it.

Then you proceed to focus on some obscure bug that 99.9999% people couldn't care less about, with implication that since this bug is not fixed whole language is crap. I don't even know how to address this - do you seriously expect this be taken as an argument?

That bug is not a big deal by itself, but the circumstances surrounding it are a symptom of severe problems with how PHP is developed.

I don't see any "severe problems with how PHP is developed" that have any relation to this obscure issue, only importance of which is in its use for bashing PHP.

The ones I see:

1. Ad hoc language design process (if you can call it that at all) resulted in a serious lack of forethought in the language's case sensitivity rules. Somehow they ended up with about half of the language being case sensitive and half being case insensitive. Somehow they ended up not considering the implications of "case insensitive" with regards to internationalization, and thus ended up with utterly bizarre rules where code works or doesn't work depending on the locale it's run in.

2. Extreme emphasis on backwards compatibility means an unwillingness to fix the bug by e.g. making the language fully case sensitive, or regularizing the rules for case-insensitive comparisons among language identifiers to be locale-independent. This could be phased in over a long period of time with progressive deprecation to ensure that anyone relying on the old behavior has years of notice to fix it.

3. Somehow, the broken case insensitivity of these identifiers also breaks case identical lookups for certain names. Despite the bug existing and being discussed for ten years, this still doesn't work. No matter how bizarre your case-insensitive comparison rules are, there is absolutely no reason whatsoever that looking up a class using the exact same byte-for-byte name should fail. That this hasn't been fixed means that either the PHP team doesn't care, has no idea how to fix this, or the code base is too broken and crufty to make a fix practical. None of these alternatives says anything good.

The issue itself is not that important (unless you're Turkish, or running on Turkish servers, or somehow end up running in a Turkish locale), but the fact that it exists and has not been fixed in a decade means something is seriously wrong.

1. As opposed to what? Government-appointed committee with 20 volumes of bylaws? Open source design processes are ad-hoc in 99% of the cases, and from what I saw in business so are many of the successful ones in business too.

>> Somehow they ended up with about half of the language being case sensitive and half being case insensitive.

Why you think it's because of the "lack of forethought"? Case-insensitive methods/classes were decided to be so for a reason (since it made easier to write bigger projects in PHP). You may not like this decision, but it doesn't mean everything you disagree with is because nobody thought about it.

>> Somehow they ended up not considering the implications of "case insensitive" with regards to internationalization, and thus ended up with utterly bizarre rules where code works or doesn't work depending on the locale it's run in.

Again, the only reason why that bizzare situation with Turkish locale exists is because it wasn't noticed. There's no deep and mysterious reason rooting in flawed PHP design why it can't be fixed - as far as I can see, the fix is not hard either, it just that nobody got to fixing it.

2. Changing language implementation with potential of breaking of 99% of existing code is not a "bugfix". If you don't understand this, maybe it's too early for you to lecture people on how to design languages. It can be done, but there's no reason to - it would lead to massive breakage with no upside in any functionality.

3. "The issue itself is not that important" - BINGO! You said it. If the issue is not that important, why you're wasting time dwelling on it and make it sound as if this is the most important thing ever? You wrote a long post supposedly about deep flaws in PHP design and process - but the only thing you actually wrote about is an obscure bug that you yourself admit is not important! Maybe it's time to discuss something that is important then?

That quip would also be an argument against error-correcting codes. Whatever I think of PHP I'm not gonna look to Confucius for engineering advice. (Now Laozi on the other hand... :)

As far as arguments about ECC, I always enjoyed the parody of a saying attributed to JWZ: 'Someone has a problem and they think, I know, I'll use error-correcting codes! Now they either have 0 or 2 problems.'

Heh, I hadn't heard that one.

We get it, man. PHP sucks, you're cool/smarter/better because you use something else, and you need to remind us all about it by jumping in every time the letters P-H-P are seen in sequence to let us all know how it sucks by retreading the same old lines used by the last fifty guys who said the same thing but to your credit you really tried to be clever about it.

A good portion of why people like to mock PHP is due to the way people end up using the language rather than the language's ugly parts. This guide is a great step toward pointing people in the right direction with the language. PHP has come a very long way and continues to improve. A big chunk of the battle is having decent guides to replace all the crap that's out there showing new PHP devs the wrong way. So why not talk about the merits of the guide rather than taking an easy opportunity to shit on PHP. It's really gotten old.

Hey, remember when JavaScript was like the worst language ever and everyone felt the need to remind everyone about that constantly? I do. And now all of them are writing blogs about how awesome node.js is.

I used PHP for five years professionally, I consider myself as well positioned as many to have an informed opinion about PHP weaknesses and strengths. My diagnostic is that PHP weaknesses are structural, and no amount of guidance can fix that. If facing the choice, one should not choose PHP over other solutions. (It happens also that I am working in Chinese tech sphere, where many startup choose PHP just because it is used by Facebook and Wikipedia, which is really sad.)

However, I appreciate very well the need for such a guide when you have no other choice. I did not read all of it, but it is certainly necessary to have strong coding conventions and a defined set of "must do/musn't do". I remember we had even built a code checker that was forbiding the use of many php functions and syntax, and had a set of wrappers around basic functionalities like string functions or date functions.

> I used PHP for five years professionally, I consider myself as well positioned as many to have an informed opinion about PHP weaknesses and strengths.

Yeah, that doesn't mean anything. In fact, to be frank, when I read that, I fill in the underlying context:

"I used PHP for fives years professionally, and the code was horrible. Granted, it was code I wrote because PHP let me write code that way..."


"I used PHP for fives years professionally, almost a decade ago..."

> I remember we had even built a code checker that was forbiding the use of many php functions and syntax, and had a set of wrappers around basic functionalities like string functions or date functions.

Yeah, that didn't do much to change my mind.

Any reason for the personal attack (based on unfounded assumptions)?...

No personal attack. You used your experience to justify your position, which really means nothing. You then went on to describe practices that, if written accurately aren't in anyone's book of good things to do.

If you take it personally, thats your issue, not mine,

I’m not the OP.

He doesn't defend PHP as a language.

He is sharing some useful guidelines to approach it more properly and help people that are still using it.

I, for one, am a fan.

> A good portion of why people like to mock PHP is due to the way people end up using the language rather than the language's ugly parts.

Are you really going to trot out that old lie?

Why not read this, instead? http://me.veekun.com/blog/2012/04/09/php-a-fractal-of-bad-de...

Because huge swathes of that blog post have already been debunked ad infinitum (here on HN, no less).

Yes, how dare he talk about the problems with PHP in the comments on a site dedicated to talking about how to avoid problems with PHP. Seriously, WTF? Are people actually offended that discussion of PHP's defects take place in a conversation about PHP best practices?

Offended, no. Weary of rehashing the same arguments against using PHP at all, when that is clearly not the point of the discussion...absolutely.

I think it is because we (as a community) should be past the piling-on stage and on to the constructive discussion stage. Snark doesn't add to the discussion.

I don't intend to jump into the ring, but as an observer, I don't think we're at that point yet. Here's the progression of the current anti-PHP flare up:

  Jeff Atwood says PHP sucks
   |- Says we should make other languages fill in on what PHP does best
   |- Post goes on HN
      |- PHP apologists say "No! PHP is fine, I've made a career out of it!"
      |- 'Atwoodians' continue to reject PHP, ruby/python need to be more accessible
      |- PHP apologists make reasonable arguments for why PHP isn't as bad as everyone says, while admitting its probably worse than python/ruby

There remains a conspicuous lack of response from the 'Atwoodian' camp regarding what could be done to add PHP's quick-start strengths to other languages so that PHP developers can develop similarly to how they currently do, just with a less wonky and problematic base language.

By no means, as an outsider, do I perceive the PHP apologists as having redeemed PHP to the point that the discussion should be about 'how to fix PHP' rather than 'how to discourage its propagation' as was originally put fourth in a fairly reasonable way by Atwood.

I realize why saying 'PHP apologists' is problematic, but I'm mostly seeing responses that are in themselves critical of PHP, while espousing its widespread use, quick-start capabilities, and developer intertia--and not espousing why the fundamentals of the language are better of the equals of ruby/python.

While I can't speak for others in the "Atwoodian camp," I for one think Atwood's article was that response, to a large degree: it pretty much said that his next big project is trying to bring those strengths to a platform built on another language.

Having said that, it seems to me that there's certainly a fair amount of work being done to make deploying apps in other languages pretty simple. With mod_passenger, for instance, setting up a Rails app under Apache isn't notably more difficult than setting up any other Apache virtual host. Deploying Python web applications isn't quite as simple yet (at least in my experience), but it's nothing that should be beyond the ken of someone who's figured out how to write a Python web application in the first place. And that, in turn, isn't really beyond the ken of anyone who's learned how to write reasonably good PHP MVC code.

Well… Javascript does suck. No one in their right mind defends the language.

Javascript is just Scheme with a C-like syntax and a limited number of bad design decisions (like automatic semicolon insertion and the == operator). PHP is a never-ending fountain of bad design decisions, because its core devs continue to make new ones.

No, Javascript is not "just scheme" with a few bad design decisions. They have significant differences.

Scheme has:

  call-with-current-continuation http://people.csail.mit.edu/jaffer/r4rs_8.html#IDX509
  Tail Call Optimisation
  A numeric tower http://people.csail.mit.edu/jaffer/r4rs_8.html#SEC50
  A Code/Data equivalence and therefore macros
Javascript has:

  Prototypal inheritance
  Every 'object' is mutable bag of string indexed properties
There's a pile of differences, even just at the semantic level before you get into the syntax or the equivalence semantics.

I understand that if you take a specific subset of javascript, you can write code as-though it has some scheme semantics (minus call/cc and TCO), but that's true to a similar extent of any language with lexical scope, closures and anonymous functions.

What bad design decisions have been made in PHP in the last 5 years?

Using '\' as a namespace seperator? Just off the top of my head, there are probably loads more.

What makes that explicitly bad?

I've actually gotten used to it (and I rallied against it heavily). It's really not so bad; it's even somewhat nice it has a file-system like connotation. PHP's design precluded using any existing operators.

Based on how long it took to introduce the ability to say foo()["bar"], I'm guessing it's not the language so much as it's a set of poorly designed parser rules.

Also, magically, I can't use empty(functionResult()); but I can say $result = functionResult(); empty($result);

> I'm guessing it's not the language so much as it's a set of poorly designed parser rules.

There are poorly designed parser rules but the namespace operator is not due to that. It's due to the fact that a single PHP file will be compiled to byte code without knowing what the symbols represent until runtime. The separate operator is needed because names are resolved before execution begins and before the symbols are known.

> Also, magically, I can't use empty(functionResult()); but I can say $result = functionResult(); empty($result);

Empty is identical to the not (!) operator except that empty() can operate on undefined variables, undefinted array keys, or undefined properties. empty(functionResult()) doesn't make any sense because functionResult() can never be an undefined variable. You just use !functionResult().

really? add: floating point everywhere, objects that act like hashes but not exactly, fucked up scoping rules including global by default, the braindead Dom API, a severiously limited standard library, and brain damage coersions to the list...

I'd leave the DOM API out of it, that's not really the languages fault.

Well, its the first one hat offered it, isnt it?

It is actually a very strong language with a few very well known warts (like every other language on the planet has). The problem is that people try to use it as if it were Ruby, PHP, Python, Java. One can do that, but just know that it is an exercise in futility. It will cause frustration and one will come to the conclusion that JavaScript sucks when in fact, it is just that most people don't really take the time to _understand_ JavaScript.

JavaScript could stand to be a bit less verbose (look into CoffeeScript for some relief if you value your sanity and time) in some areas and type coercion should just go away; but if you use strict mode and strict equality, a huge amount of pain is alleviated.

If one take the time to learn about constructor functions, the prototype chain, and own properties; they are 70% there. Most people can get by on just that.

curl -s http://getcomposer.org/installer | php

is creepy. Never ever run other people's code without at least giving it a glance.

Reminds me of how you get mysqltuner:

wget mysqltuner.pl

perl mysqltuner.pl

(Yes, they actually have a .pl domain for it)

RVM's installation is similar:


A far cry from the safer/verified "download this and check it's MD5 checksum" method that I'd prefer.

Seriously, fixing package management so we can continuously integrate arbitrary code would be great. Getting arbitrary OS package creation to be almost as easy as pushing code to GitHub seems like a very worthy goal.

md5 is not going to protect you from much, especially if the md5 checksums are hosted on the same server.

Also, pushing random code via apt-get is not going to win you any sysadmin friends. They like their servers to be stable, and their packages to be well tested.

Seeing as you can remove said code via apt, you'd likely win them over compared to the alternative of being told to install compilers or some other non package managed software bundler like cpan/rvm/npm that can't be canned and easily deployed.

But why would you remove it? Because whatever you've installed has broken.

Much better not to be broken in the first place.

It seems you live in an idyllic world far, far away from reality.

It's not the nineties anymore, MD5 doesn't protect you from much, and especially not from the author of the original package creating an alternate version.

Viable verification is based on an unbroken hash (preferably SHA-(256|384|512), but SHA1 still not broken even it it's definitely too short nowadays. And the hashes need to be distributed properly, either PGP signed or hosted on a trusted TLS protected site...

Yet many projects still distribute MD5 hashes, thinking it got any value.

For the longest time the installation instructions for NPM were almost exactly the same. But its worse when PHP does it :)

In terms of security this is no different than executing someones binary or building a big code base.

Indeed, especially coming after this further up the page:

> Never ever (ever) trust foreign input introduced to your PHP code.

Where'd I put that sense of irony...

Except that there's a significant difference between "trust" of input from the user vs. "trust" of the software stack you use as a foundation.

Unless you've read every line of the Linux kernel, we all succumb to the later point sooner or later.

If you don't like that command, do this instead:

    > curl -s http://getcomposer.org/composer.phar -o $HOME/local/bin/composer ; chmod +x $HOME/local/bin/composer
Assuming that $HOME/local/bin is in your $PATH, the current user will have a "composer" command available.

Yeah... only idiots "sudo aptitude install" without reading and building from source first!

You really can't tell the difference between blindly executing input from an insecure HTTP connection, and installing packages with a tool that verifies cryptographic signatures against known good keys shipped with your distro?

Mr. Cantor, I have added to the list of people to never hire I keep in my notebook.

You can explain the difference without attacking the person you're replying to.

The risk of picking up malicious executable from the legit server is far higher than that of picking up a malicious executable from an impersonating server. Practically speaking.

So? Who says the verified package isn't malicious? My point isn't about cryptography, it's about complexity. Unless you personally read through every line of code, how do you really know that there isn't something in there waiting to screw you over?

I trust my system's package maintainers and the signing makes sure that it is them.

I do not trust a random website that could easily be MITMd.

So you'd be fine with https?

You don't know. What you know however is who to sue if the package ends up being malicious, thanks to the signature.

And I've added you to the list of guys that think they are "the shit" because they have hiring abillities (in some shitty company) and need to tell it on the intertubes.

haha. Always good advice. But I checked. It's fine :)

It's fine now until someone hacks their site or poisons their DNS.

Or writes a script which checks the user agent and only serves up malware to curl.

Or the second time that an IP address hits it.

Or something else that you haven't thought of.

Update: Such as doing something nasty to http://getcomposer.org/composer.phar instead - a 520KB php file that the first script downloads and runs without even md5ing first. Did you audit that too? Did you understand everything that it was doing?

Or social engineers their registrar and changes their dns.

That's really just a question of trust. If you know what Composer is, you trust it.

'apt-get install whatever' is just as magically scary and dangerous.

No it isn't, there's GPG signing and things going on there.

  No it isn't, there's GPG signing and things going on there.
That's really just Cargo Cult security, isn't it? Signed packages can just as easily be malicious. In fact a repository server could be a much worthier target for the injection of bad code than a single, relatively obscure web project.

The repository doesn't have any access to the developer's private key. That's exactly the attack that they're designed to mitigate.

The difference is the same as between http and https.

Exactly. SSL doesn't guarantee that the content is benign either. But there is also a key difference when it comes to software distribution. On a typical web connection you worry about 3rd parties observing your content and maybe even spoofing it later (e.g. stealing your cookies), but as far as downloads are concerned your main worry is actually content integrity. This integrity is threatened by both malicious publishers and outside attackers injecting malicious code into otherwise benign software - having a GPG signature alongside your rpm does (almost) nothing to mitigate that risk.

Not sure if you are trying to make a joke (and if so, it's incredibly subtle), or you are being serious. In case you are serious, to explain how HTTPS as it's used means anything about the trust-worthiness of the two parties involved?

Look at the original post. "curl -s http://getcomposer.org/installer | php" It's not just about trusting Composer, it's about trusting every point between you and their server. If I want to know that I am actually executing Composer I need to use a secure download method.

I don't disagree with you, but if you've got someone actively trying to exploit you sitting between you and the Internet, you've got bigger problems.

Someone trying to find an exploit is a bigger problem than giving them one?

Oh, definitely. If someone has a launched a targeted attack against you and they already have the ability to seamlessly view and modify your internet traffic, you are in pretty serious trouble whether you download your development tools from wget or apt-get.

Except that apt-get will check GPG signatures and detect that kind of attack. How is a MITM attack going to find a 3rd party's private key?

I'm looking at the post you replied to. So maybe you replied to the wrong post, or ignore context and tried to be witty or smart.

In context, what you say makes no sense.

Regardless, https would be better, but if you are that nervous as you suggest you are, then https doesn't solve your problem either. Neither does some hash thrown up on some site for you to compare against.

Here, how about I summarize my view of the conversation for you.

  aw3c2: 'curl | php' is creepy
  timaelliott: apt-get is just as scary
  kudos: no, it has signing
  udo: that's cargo cult
  me: no, it protects like https (meaning it authenticates and stops MitM)
I was responding perfectly in context to point out how the protections apt-get have are useful. I also tied it back into the original comment but you can ignore that part if you like. I don't know why you think I was 'trying to be witty' and ignoring context.

Ahh, gotcha, that better explains it.

Still, https doesn't validate anything. You could add a certificate, but then that only means you are talking to the server assigned the cert, not that the actual package is good.

I still stand by what I said: mountain and mole hills.

It does not help you if the originating server has been hacked, which is by far the most likely attack vector (after people being assholes on the internet or making mistakes in their script).

Protecting against that is the whole fucking point of using things like apt-get/PEAR and GPG/code signing.

Signed packages can be just as malicious, but the security of the mechanism relies on the signer not wanting to do jail time, thus protecting his secrets and not signing stuff he doesn't trust.

While PSR-1 has pretty good universal guidelines, PSR-2 goes too far in insisting on subjective preferences (spaces over tabs, 80-char lines, bracketing styles). We should not pretend that there is a "correct" answer to these choices, just as long as they stay consistent on a per-project basis.

All told, I love site, and I hope it keeps iterating. PHP may be ugly, but it's powerful, and most of its bad reputation comes from good coders having to pick up the pieces from bad coders.

PSR-2 isn't trying to say that there is one correct answer. Instead they're trying to provide a single answer from the many valid possibilities.

"When various authors collaborate across multiple projects, it helps to have one set of guidelines to be used among all those projects"

I'm not saying it shouldn't exist; I'm saying it shouldn't be recommended at all as part of "PHP The Right Way". It mixes up arbitrary personal preferences with universal best practices.

Exactly, this is what infuriates me about the arguments and whining against PSR-2.

Spaces, Tabs, OTBS, whatever. It doesn't matter which one was chosen, just that something was chosen. Ask the Pythonista's what PEP8 did for their developer's ecosystem.

Also it's important to note that that PSR-2 was based off already existing coding standards like Zend's and Symfony's.

And what do you do with all the coders like me who would refuse to change their habits? Does the Python community have tabs holdouts who are github lepers because no one wants their code "infected"? (I don't do much in Python, I actually don't know what the community norms are.)

I think it's silly to pursue per-language consistency; it's a pipe-dream that just leads to more religious wars over minutia. Per-project (or per-organization) more than suffices.

>And what do you do with all the coders like me who would refuse to change their habits?

Reformat their code.

As for "per language consistency", Go does it just fine...

I didn't understand this:

    4.2. Properties

    This guide intentionally avoids any recommendation regarding the use of 
    $StudlyCaps, $camelCase, or $under_score property names.

    Whatever naming convention is used SHOULD be applied consistently within a 
    reasonable scope. That scope may be vendor-level, package-level, class-level, 
    or method-level.

    4.3. Methods

    Method names MUST be declared in camelCase().

Methods should be camelCase(), but properties (fields?) can be any convention as long as its consistent throughout.

Yup, that's my basic reading comprehension dropping out again. Thank you, that does make sense.

It looks clear to me. Properties refer to object properties or variables and Methods refer to object methods or functions. This standard recommends three formating conventions for variable names and requires that all functions be written in camelCase.

What don't you understand specifically? It can't be any clearer, and it's obvious the reasons for this with what the PSR is. So, I'm confused as to what you find confusing?

Something to consider mentioning - there are some in PHP these days that take this sort of stuff a bit too far. Drives me nuts to see people writing classes to encapsulate a 3 column database result. So much overhead and boilerplate.

I think that is kinda mentioned in the popular framework bit of the document.

You should check out Java sometime.

The problem is not Java, but some types of architects that flourish in corporations, usually doing designs with endless numbers of abstractions, layer upon layer.

I've seen this happening in C, followed by C++, and now Java and C#.

They will do it regardless of the language being used.

This is an excellent point. I so often attribute my disdain to Java itself when, in reality, the issue is the majority of Java engineers.

Java itself can be a beautifully terse language.

"terse" is about the last word that I would use to describe Java.

Compared to almost every other language I've had exposure to, it's more verbose.

I usually don't like to put "beautiful" and "terse" next to each other. "expressive", maybe, but terse? That sounds like an insult.

That's exactly my problem with it. It's just that when you do in PHP, you don't get any of the benefits you derive from all the Java BDSM.

Java still gives me nightmares ;(

As a part-time PHP hater who often has to work with it professionally, I believe this is a fantastic resource. The bit on databases in particular is something that all PHP devs should read.

That said, it is difficult to bring a legacy code base in line with modern style, though you can improve it over time.

Also, this could benefit from some other gotchas, extremely surprising behavior and best practices for avoiding common pitfalls.

On a database section, I am not a fan of PDO and I choose native interfaces like mysqli for my DAO layer or opt for something high level like ORM depending on the requirements.

But it goes without saying that protection from SQL injection is a must, it is just PDO's statement binding is not the only way. MySQLi does support data binding, and for others it is easy to DIY using sprintf and whatever is the escaping method target native driver implements.

You can use PDO to connect and run queries without using all the crazy variable binding features.

DIY and SQL are not two things you want to see together.

One point in and its already dead wrong, you never filter input, only output.

Edit: Everyone talking about databases: paramaterized queries, check them out.

Agreed, most input should not be filtered. There are some exceptions though like stripping whitespace and dashes from credit card numbers and phone numbers.

The filtering of input has nothing to do with security (that should be handled by output escaping and paramterized queries) and should only be used for improving the quality of the saved data.

I'd definitely filter input that goes into a database. But if you think the wording can be made better, definitely send a pull request. Thanks!

You've been downvoted but I completely agree. You cannot sanitize text for all possible situations; you can only escape it depending on the output format (database, html, etc).

These functions should be used to "validate" input rather than "filter" it.

I absolutely hate how for example phpBB creates garbled bbcode in the database because they thought that they should filter it or something, instead of doing it on output now every consumer of the data has to unfuck the content, because they messed up.

Input is almost always filtered. Without mincing the semantics of that, let's say you receive free-form NL query as input. You don't filter that to reduce it to core terms you send to the database? You don't remove prepositions? You don't tokenize at all? Input is ambiguous and reduced/filtered into pseudo-meaningful terms to return relevant output.

If I want to tweet

  I <3 O'Reilly books
you could pre-encode that as safe to paste into raw SQL, or as well-formed (X)HTML, but you can't do both simultaneously. Either encoding would end up distorting the content in the other context. You have to encode during output (and writing to a database counts) using the rules of the system consuming that output. Lots of crappy web forums visibly mangle punctuation in a futile effort to avoid this.

What a great example. I am going to remember that one.

This is true for all structured data, but the problem always comes from freeform text fields, which you cannot filter for one context without mangling or destroying the data for all other purposes—except perhaps trivial things like trimming leading/trailing whitespace.

What's wrong with filtering input? If you expect a number, what's wrong with telling the user "strawberry pie" is not a valid value?

There's a fine line between filtering and validating. What's meant with filtering is things like add_slashes and mysql_real_escape_string, a uniform transformation on the input, regardless of it's destination.

Validating on the other hand is checking if the values satisfy the expected requirements.

You only want to apply certain filters if you know they apply the current output. (htmlentities if output as html, mysql_real_escape_string if embedded in a query).

Filtering can't be done "regardless of destination", of course, since kind of filtering depends on the required result. Otherwise, difference between filtering and validation is largely in application semantics - some may prefer one, some another. Output is different things, of course filters can be applied to the output too.

What everyone is missing with the filtering argument is:

(1) normalization (things like trim, etc. so you don't do stupid things like invalidate an email address just because it was input with trailing spaces). The result is passed to a validator.

(2) validation (if a number is expected, it's only valid if given a sequence of digits within the correct range). Valid values are passed on to the next phase (likely persisted).

Sanitization is generally not needed and in most cases likely to cause data corruption. I'm sure there are use cases for it but it should be the exception, not the rule.

SQL injection attacks alone are almost always a result of not filtering input...

This the wrong way to look at it, and yes, the PHP world always does this wrong because they're too focused on HTML.

SQL injection occurs when you're not escaping data while producing output, namely, an SQL query sent to the DB.

XSS attacks occur when you're not escaping data while producing HTML, but you don't need angle brackets to do it. <a title="$string"> allows for XSS injection with just a quote character.

Header injection attacks occur when you're not escaping data while producing HTTP/MIME headers, and all you need is a line-break character.

The escaping always depends on the output context, and the data in the database cannot be made safe for all these contexts. You will still need to allow people named "O'Brian", let people post "<_<" smileys, use Unicode in their names, etc.

> the PHP world always does this wrong because they're too focused on HTML.

No. The PHP world recommends, time and time again, using PDO and binding variables to queries. I've yet to meet an individual who does it the other way, other than people who are relying on extremely outdated tutorials (7+ years ago). Hell, even this document does. This document, unfortunately, uses the word filter in the wrong way, but the intention is still fine.

One thing I've run into is that PDO does not let you parameterize the field name in "ORDER BY" clauses. And there are a few other little things that I've wanted to do that it doesn't allow. It may be that me even running into these problems means I'm doing something wrong at a structural level. Regardless, in those statements where I want something to be dynamic, but it's not allowed by PDO, I do an exact equality check against a white list.

Well, that's not what binding is supposed to do. After all, field names aren't something you should be exposing at all.

> I do an exact equality check against a white list.

Pretty much the way you are supposed to do it (except, I'd actually use the value in the white list rather than the matched input value, as the two should not be the same).

Which is fine for SQL injection, but completely ignores every other context, of which there are many, and which don't have PDO-like APIs. That's what I meant by PHP getting it wrong. The entire filter pipeline is built to assume you're outputting only to HTML, and it's useless for making data safe for other contexts without completely destroying it.

I suggest removing the section about filtering entirely and making sure the section about PDO explains SQL injection briefly.

I'm not the op, but I'll keep that in mind fora push request. I think filtering just needs to be renamed to validation, and improved (but then that was the point of posting it here I imagine).

In my anecdotal experience SQL injection attacks are almost as often caused by relying on filtering data and then forgetting to filter it for some fields. You should instead rely on parametrized queries and only use string operations to build queries where you must (and then do it very carefully).

SQL injections are very rare to non-existent in code where the programmers generally rely on parametrized queries.

With parametrized queries, that becomes a non-issue, but I still see no point in cluttering the database with data that's just going to be filtered out at some point - might as well filter it before it goes into the DB to begin with. The exception, of course, being those rare cases when some users need to see the filtered data and others need to see the raw data, but even then, you likely won't want to allow everything.

I am not sure if you are referring to the same sort of filtering mentioned in the document. The data is filtered before it hits the database layer, this saves resource being used.

That's what I meant. I just kind of articulated it poorly, my apologies.

Parametized queries are just another way of filtering input ..

No they're not. They're a method for ensuring that what is meant to go into some field in some database actually ends up there and does not start doing things it should not be doing.

Yes, but on the site, they make a clear distinction between parametrized queries with PDO and other types of input filtering. I misunderstood and thought you were referring specifically to the latter.

It's sometimes known as sanitising input, so I'm guessing that's what they were trying to refer to.

Output is not what goes to the user/page, in this context it is what your code sends anywhere, such as to mysql_execute or something

I'm wondering why a specific code style is 'enforced' while it has nothing to do with interoperability.

Libraries with different code styles can be used together without problems. It seems like they are using the PSR to declare they're own style as superior.

PSRs where decided based on the most common standards used by some of the biggest PHP projects around. It wasn't a single person setting a standard. PSRs are completely optional.

However, you miss the point. The point of this isn't really to define all the options. Rather, it's to spell out best practices (and PSR-0 is really a best practice, and all about interoperability) that the community generally agrees with. Better to have a standard coding style than to have none at all, and if you have to choose one, PSR-1 and 2 are an excellent choice (considering how it was devised).

Im sorry but accepting underscores as a valid alternative to namespaces in 2012, is not a "best practice".

The whole concept of PSR-0 is ridiculous anyway, because PHP supports registering multiple class loaders. If a project wants to use a naming convention that won't work with standard spl_autoload(), they can register their own autoloader.

except if you've ever had to work with lots of different autoloaders at once you'll know that you regularly get conflicts, and getting the correct autoloader order is often a case of trial and error. Using sane conventions across libraries avoids all of this mess.

i wouldn't call using underscores for namespaces and forced filenames "sane".

The built-in spl_autoload offers better support for modern code than the PSR-0 recommended autoloader

The reason for underscores as namespaces is simply that some older libraries want to maintain compatibility with 5.2X for whatever reasons. Of course it's encouraged that newer libraries are written with proper namespaces and almost all of them are.

I think it's less about being "superior" than standardizing on a common style. Makes it easier to get up and running with someone else's code. But if your team agrees on a common but different style, that's fine too. It accomplishes the same goal. I'm only suggesting the official standard for new PHP developers.

Right. I think the main take-away from it is to be consistent and make sure everyone on your team is on the same page about the coding style. I see the PSR as a basic set of good recommendations, rather than something that must be followed. It's a good idea to follow it, but at least follow something.

My only complaint with it personally is that I Can. Not. Stand. putting opening brackets on their own line.

I understand it's not an either/or situation but...

I'd MUCH prefer people spend time writing tests for their code vs debating/arguing/refactoring code style. If your tests and good and coverage is high, there's far less chance I should ever even have to muck around inside your libraries, much less modify them.

And again, one doesn't preclude the other, but I see so many people making a bit stink over style - tabs vs spaces et al years before the PSR stuff - yet rarely do I see even 20% of that effort spent on getting people to test.

I say this not as someone who tests everything 100%, but as someone who doesn't do much of it, and understands the importance of it. When I'm deciding to use someone else's libraries, I never make a decision based on the code style they've chosen - I base it on maturity, documentation, and tests/examples provided (when there's a choice, sometimes you don't have a choice, or you roll your own). The really good libraries? I never even have to look a their code - it might be all run together on one line for all I care - it just works.

If a library works like it should, then you may never have to look at it - that's great. But if you're working on a team, you'll have to read and understand other people's code all the time, and even if you're not, someone, somewhere, is going to eventually want to make that library do something different.

I agree that, of the two, good test coverage is more important than pretty formatting, but a good code style is going to make the code easier to debug when those tests fail and easier to extend when the library needs to do more. It's a simple matter adopt a coding style that works and stick with it, so there's really no good reason not to do it.

By comparison, it does seem like a trivial thing to obsess over. There are a number of coding styles which are all fine in their own right. I think people should worry less about the specifics and more about the overall intent-to write consistent, clean code. How many blank lines you have after block of code or where you put the opening bracket doesn't really mater in the end, as long as you follow the same structure across the whole code base.

One of the arguments/justifications for the PSR standards is to encourage interop of libraries (to be able to mix/match from various frameworks and projects).

Standardizing formatting for a team/project is not a bad thing, certainly, but if there's competing styles on a team, but they're making good progress - hitting deadlines, high test coverage, good/deep engagement with stakeholders, etc., code formatting is just not something I'd bother enforcing. It may be a later step to go back during a project post-mortem and get the code ready for 'deep freeze', assuming the project is 'done', but how often does that happen?

My perspective is probably a bit different than some here - I freelance, and work in multiple languages for different clients, often concurrently. In a 6 month period I had 2 PHP projects, 2 Grails projects and a Rails project, each running for several months and overlapping. I worked with a different group of people on each project, each with varying skill levels and backgrounds. I adopted my style/technique as best I could for each project, and didn't harp on formatting with anyone, because... it just really doesn't matter. What does bug the heck out of me is someone rechecking out my code, spending time reformatting it, then checking it back in, and counting that as 'work', when there's many many many other issues needing to be worked on.

It does help improve your interoperability with other developers and other code though.

Python has had PEP-8 for quite a while now, and it definitely helps in improving both code quality and understanding random libraries that you find on the internet. It doesn't catch everything, but then that's what Pylint is for.

There's an easier-to-read version for those who don't like PDF: http://jeena.net/images/2012/php-the-good-parts.jpeg :-)

I dont agree with the article all the way but it's certainly refreshing to see people trying to improve PHP coding practices instead of just complaining. Very well done.

That being said... Every language has its strengths and weaknesses. There is nothing fundamentally wrong with PHP (except maybe that if you look at it it's not a very exciting language, even a bit boring). Security for instance has nothing to do with the language itself. And as for PHP syntax, it's a blessing compared to some other languages; at least we don't have a semicolon debate in PHP land ;-)

The comments about namespace are somehow ironic: is it very common to find developers that know what classes are but not namespaces? The namespace concept is much simpler than class. Which makes me wonder: who is the target audience?

possibly. Namespaces are very new to php, so programmers who taught themselves via php might not have much experience using or general knowledge of them

It's only been in the last 2 years or so the php web hosts have upgraded to version 5.3, which is when namespaces were added.

There are a LOT of long term php developers who have never used them.

What I hate about namespaces in PHP is the separator they have chosen \.

Hey, nice work. Wouldn't a wiki platform work better however, instead of git?

Edit: also might be worth adding a bit about steering clear of phpclasses.org as well as w3schools, they bother contain far more bad, than good code.

Will be moving over to GitHub pages w/ Jekyll soon to automate build process.

Git (along with Github) may be better because of the higher control that you have over the development/writing with a not-so-high management work (you don't even need to have a git client in order to change content since the content is hosted on Github). It is easier to manage different versions, apply patches and so on. Dokuwiki might work well for this purpose because its (almost) 0-config setup, though.

Are there any good books (or other resources) on modern PHP?

I last used PHP back with PHP3 (and then went C++ => Java => Python => Python/JavaScript => Ruby => Python/R), but a bunch of code I want to read at work uses PHP (with Zend). I no longer remember most of what I learned about PHP3, though obviously the PHP syntax seems to be at least somewhat readable as a sort of amalgam of Perl and C++ syntax and idioms. What does, e.g., Facebook use to get engineers who don't know PHP (but might know C++ or Python) up and running?

As far as I know, at Facebook we don't give pre-emptively/usually give people a book to learn PHP. Those that don't know PHP (or are rusty) can generally get the syntax/keywords right in an hour, and then there's a longer time spent getting familiar with both the standard library and our own frameworks/libraries.

There is a lot of good code to look at and learn from, and the Bootcamp program teaches a bunch of our own library and some guidance on what good and bad standard library functions are for certain cases. We also have a "newbie" group where people can ask questions about the codebase. And if you do something without knowledge of a built-in (or Facebook) function/class and make things more complex than they need to be, your code reviewer will let you know how to do it easier/more idiomatically. Every once in a while there are language tech talks, and sometimes even whole-day training sessions (we did one on exciting new C++11 features).

Besides that, I definitely spent a lot of my time with php.net/function_name open and exploring when I couldn't remember all the functions available or the parameters and order.

"Real-World Solutions for Developing High-Quality PHP Frameworks and Applications" by Sebastian Bergmann (referenced in the original article) and Stefan Priebsch. It won't go in to things like "how do I use usort" but it touches on important things like testing.

I suggest that you open up the doc source on github so that you can attract contributions from people while still maintaining editorial control.

A good example is: python-guide.org -- http://docs.python-guide.org/en/latest/index.html

As mentioned elsewhere in the comments, I'll be moving over to GitHub Pages tonight to do exactly this.

There is a bit in the Introduction section of the doc that says how to contribute. Its actually just a one page on github at the moment that you can fork and send in pull request.

Why the hell is required space indentation instead of tabs? Don't you know how to setup your editor? Don't you know that there are coders with special needs and they would like to setup another indentation, because they are using e.g. font size 20px to see your code?

this is great stuff - I'm a casual php hacker and this is just the sort of thing I need to help me out when I'm working in the language - saves me from having to be deeply embedded in the culture of a language I don't use "all day every day"....so thanks!

This is a very nice guide for everyone that has to work with PHP.

Nice read. TIL I should be doing some things differently in PHP.

Really hope they fix the formatting. Unreadable for me, the font is way too big.

    user:	kaolinite
    20 year old Python/PHP/C developer
That font will be just perfect for you in about 15-20 years.

I'm 20 too and always read articles with 300%-500% zooming if there is no vertical scrollbar. Occassionally putting the glasses down and still be able to read is a huge relief!

In 15-20 years, I will zoom as required. The issue really is less the font size and more the way the text stretches to the window, so if you zoom out then the sentences become far too long. I ended up having to alter my browser window size.

Edit: Just checked, definitely just the stretching, though a bit smaller would be better for me.

Tangentially related: Smashing Magazine recently did an outstanding article on readable web typography. (See http://www.smashingmagazine.com/2012/05/02/applying-macrotyp...). They say 8-12 words per line is ideal, though their example exercise seems to average closer to 15.

Hold ctrl and use the scroll-wheel on your mouse to zoom in and out.

PHP: Not even once.

Right way to write PHP indeed. Sometimes I wish PHP itself was written this way.

Oh! The guide does not mention the case: if a class contains only one static method, please, use a function. It does not look as educated, but it's obviously a function.

Not PHP specific, I admit.

Perhaps I'm misunderstanding what you're saying, but standalone functions cannot be namespaced or autoloaded. Static methods solve both of these problems. With late static binding there's no reason to avoid static methods any more.

Oh god yes. I ran into an extreme case of this recently. 200 something lines of class definition, class variables and internal private methods that end up chaining 5-deep, with a single public method.

Refactoring to a single function took it down to under 20 lines.

I wish I knew what motivated people to do things like this.

From my own experience, PHP developers who are introduced to OOP often get taught the Java-esque flavour of it. Classes for everything, abstractions and base classes and inheritance all over the place.

Hell, I even went there myself at one point, at first doing it to DRY up a bunch of procedural scripts, but later introducing more abstractions to bend the existing code to my will.

Now, I prefer simplicity and will often scrap code that jumps through all sorts of hoops just to do something simple.

pretty sure it's the same thing every time: coming from working on really big systems that need that much depth of abstraction to something simple that can be done in 20 lines and forgetting, or not understanding how to scale down. most common with c# or java coders doing client libs for php for their application.

It would depend on what else is in the class - descriptive class constants used by the one static method wouldn't be possible if it was 'just a function'.

I think that Lithium (www.lithify.me) would be really great to mention under the 'popular frameworks' section.

Thanks for the suggestion. Feel free to send a pull request and I'll be happy to add it in!

I like it. Would be smart to add some kind of picture for sharing Facebook is more successful if people not just see text.

lol. downvotes for wanting to share someone's idea. that one I really don't get...

Probably because your comment is extremely difficult to understand and looks a lot like spam.

What is hard to understand about it? Most link sharing happens on facebook. If you share a link in facebook, people will click on it, IF there is a picture that interests them. If there is no picture 99% of people will ignore the shared link. So for the author of this website it would make sense to add any picture at all. When someone shares the link to his website, FB will automatically find the picture. But there is none.

What's hard to understand about it is that it's a mishmash of words thrown together with no coherency. Your point about having an image to make Facebook sharing makes sense, but there's no way to extract that point from your original post.

There is a dot missing between "sharing" and "Facebook". I just see that now. If there are more grammar issues, I am always open to learn. It's not my mothertounge, though. And I think I have that attribute in common with a lot of readers here...

These guidelines won't save you from some bullshit PHP "rules", such as: http://stackoverflow.com/questions/5810168/php-foreach-by-re...

How is that a "bullshit PHP rule"? If you for loop in C, setting a pointer each iteration, you would expect the pointer to still be set the the last assignment in the loop once you're out of it.

C lets you define variables with block scope:

  int main(int argc, char *argv[]) {
  	for(int i=0;i<10;++i)
  		printf("%d\n", i);
  	printf("%d\n", i);
The last line fails to compile—'i' is no longer defined after exiting the loop.


  public static void main(String[] args) {
  	for(int i=0;i<10;++i)
That also won't compile.

Coming from a language that supports variables with block scope, PHP's behavior is very surprising indeed. If the first mention of $object is in the loop, I can understand someone expecting $object in the second loop to be a distinct variable that just happens to share the same name.

This behavior is even surprising coming from Perl, though for a slightly different reason:

  @array = ('c', 'c++', 'java', 'perl');
  foreach $item (@array) {
      if($item eq 'perl') {
          $item = 'php';
  foreach $item (@array) {
      print $item . "\n";
For that matter, PHP's reference semantics are a little surprising in general coming from any other language I've ever used.

I was thinking more of:

  #include <stdio.h>
  int main()
          int arr[10] = {1,2,3,4,5,6,7,8,9,0}, *ptr;

          for(int i = 10; i>=0; i--)
                  ptr = &arr[i];
                  printf("%d\n", *ptr);
          printf("%d\n", *ptr);

Sure, but you defined ptr outside of the loop. Who defined $object outside of the loop in the PHP example?

Also note that, in C, you have to explicitly dereference pointers:

  ptr = 42;
You should get a warning from your compiler if you try that. PHP effectively goes ahead and changes it to:

  *ptr = 42;
Perl requires you to explicitly dereference references as well:

  @array = ('c', 'c++', 'java', 'perl');
  $item = \$array[3];
  $item = 'php'; # Does NOT replace the item in the array
  foreach $item (@array) {
      print $item . "\n";
PHP is weird in this regard: if you ever assign a reference to a variable, later assignments go through that reference automatically. To convert the variable back to a normal variable, you have to unset it. I don't know of another language that acts like this. Can you think of one?

Combine that with the lack of block scope, and you get surprises like the example BadCRC linked.

You think PHP is weird because you don't understand references. Reference is not a pointer, PHP doesn't have pointers. Reference is variable binding. $a =& $b is not an assignment. It is a binding - it means $a and $b are now bound to the same variable/value.

No, I do understand references. I'm just trying to explain how references in PHP are very, very different from references or pointers in any other language I'm aware of, and how they could be confusing to people who know other languages well but are less experienced with PHP.

Perl does have a similar concept, but it calls it aliasing. Perl references behave more like what you'd expect coming from other languages.

I wish PHP had called its references something else. They're not really references at all.

Just because I think PHP references are weird doesn't mean I don't know how they work. It does make me wonder, though, why PHP references work the way they do. What's the benefit of doing it this way instead of the way just about every other language ever does it?

Why PHP references should be like pointers? It is "confusing" only if you have wrong preconception about how PHP references should be. If you let it go and learn what they actually are, there's nothing confusing about it. Just don't let you preconceived notion about what it "should" be block your learning about what it actually is.

Most of "other languages" similar to PHP don't even have concept close to references, except for C++. Similarity with C++ may be briefly confusing, but it's not unheard of that in different languages concepts meant to achieve the same thing work differently. Expecting PHP would match C++ in every detail or would have to invent completely new terminology altogether makes little sense.

>> What's the benefit of doing it this way instead of the way just about every other language ever does it?

"Every other language ever" doesn't do it in any particular way. Perl has pointer-like references and they are nightmarish to work with. Languages like Ruby or Java pass everything by value or by object reference depending on how you look on it, since everything is an object. Some don't have the concept of references all. Low-level languages like C/C++ have pointers. In some languages variables are not mutable, so the whole question is moot. Saying that "every other language ever" does some specific thing in this regard and only PHP does it differently is meaningless - different languages do it completely different, and PHP has its own way. It doesn't match your favorite one - fine, everybody is entitled to have one's favorite ways, but that does not make PHP "weird" or wrong in any way, just as it doesn't make C, Java, Python or Perl wrong.

PHP has references, because once upon a time it didn't have pointers. If the only way to pass pointers is by value, then you are severely limited. So it got references, following (I assume intentionally) Perl's syntax and semantics, though with its own reference counting foibles.

Then it got pointers, and references suddenly weren't needed that much anymore. But it kept the old semantics, and still needs references for passing arrays around, since arrays are not objects, and PHP assignment is still by copy.

WTF. Sometimes I wonder if I'm being unfairly prejudiced by not learning PHP myself and making my own decision about it but things like this make me change my mind.

I thought this for a long time as well. I always enjoyed ragging on PHP but wondered if it was just because I wasn't familiar with it.

A few months ago, I got the opportunity to do a little PHP programming. I was wrong. I didn't have a bad impression of PHP simply out of ignorance. In fact, my opinion of the language is now much lower than before. I honestly can't conceive how anyone could legitimately defend it for anything other than its ubiquity.

You are completely correct - you are being unfairly prejudiced by judging PHP on explanations of people that do not understand it instead of learning it. If you learned it, you would know references work exactly like they supposed to, and do exactly what they are meant to do - just because they are not, as parent assumes, pointers, he misunderstands them and thinks they are weird. Moreover, he thinks since PHP in not like C and does not have C-like pointers PHP is weird. Please read http://us2.php.net/references if you want real information instead of collection of misunderstanding.

I think the whole point here is why does PHP even have references like that. Right now the only mainstream language I know that does that is C++ and well, its C++ and mutable references are actually not frequently used in practice. Most other languages stay with pass by value most of the time and PHP references kind of look like a leaky abstraction from the underlying C implementation...

C++ references and PHP references are completely different beasts. PHP references like Unix hardlinks, for example. As for why they exist - they make doing some things easier and some use cases easier to program, without introducing concepts like pointers which are completely foreign to language like PHP. Could we do without them? Yes, probably. That's only one way to solve it, there can be others.

And in C++, a variable is either declared as a reference and acts like one, or it's declared as a value and acts like one. It can't change behavior halfway through a function.

(Well, ignoring operator overloading anyway… you could conceivably import PHP's concept of variables and references into C++.)

I use references for passing around large arrays of data for instance, rather than having copies made all over the place (class instances are passed by reference no matter what you do).

What I meant is that people usually pass things via a pointer (that needs to be explicitly dereferrenced) or via const references (where there is no mutation to worry about). Mutable references are rarer and usually they are function arguments and are relatively "obvious"

I'm just upset that you don't have braces around the inner body of your `for` statements. I want to edit the DOM just to fix it.

His indent level is set enough that it's likely not an issue.

(Yes, the "what if you add another statement line later?!" trope has been registered.)

"Yeah, yeah, I know there's a nail in my tired, but I know it's there so it's okay."

There's no bullshit except in that code. If you use by-ref assignment and later try to re-use the same variable name, that's what you get. That's what by-ref binding is designed to do. If you don't understand it, re-read the manual on PHP references. It's not PHP fault if somebody doesn't use language properly.

The result is 100% logical. My own personal guideline is to never use references anywhere; even in a foreach loop you can use the key to modify the original array instead of a reference to the value.

References have their uses, but they are not the simplest concept. For people that think references are like C pointers it is indeed better and safer to never use them. For the rest of people, in about 90% of cases you think you need them you actually don't. But the remaining 10% is still there.

The only place I can see that references still have some value is for "out" parameters on functions. But, since it's easy to do multiple return values in PHP, even that is not terribly relevant.

Applications are open for YC Winter 2022

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