Every wondered about code formatting?


I don’t know if you had a chance to check out the article “PSR-1 and PSR-2 to be Approved as Standards”. It is a set of standards that industry heavy-weights developed as standards for PHP developers to adhere to allow your code to work better with other libraries and frameworks.

The good news is it not difficult to understand these standards (not long in tooth) and fairly easy to adapt to your own code. I know my IDE allows me to set-up most of these formatting standards as default behaviour.


My early code was a mess of copy-paste mixed with hand-written. I was more interested in getting syntax right and learning how things worked. Over the years (writing in a few languages, trying different IDEs with their auto-formatting) I slowly “settled” on - quotes because it seems it’s always in flux :wink: - my own way of formatting because as the code got more complex it became very difficult to read it.

After I wrote a few MODs for phpBB I incorporated that formatting convention for my own code.

After I wrote a few plugins for WordPress I incorporated that formatting convention for my own code.

I tend to write my javascript code with the same formatting as I do my PHP code

My current way of formatting isn’t too far off those in the proposed standards, although

Files SHOULD either declare symbols (classes, functions, constants, etc.) or cause side-effects (e.g. generate output, change .ini settings, etc.) but SHOULD NOT do both.

If it’s for personal use, the file is small, and the code won’t be used elsewhere (how often has this assumption proved wrong :shifty: ) I prefer to have everything in the single file.

Code MUST use an indent of 4 spaces, and MUST NOT use tabs for indenting.

I use tabs because back when I used plain Notepad as my editor hitting the tab was easier that hitting space a bunch of times. But now that I use Notepad++ and IDEs that allow setting to tabs, I could change easily enough I suppose.

The opening brace MUST go on the same line, and the closing brace MUST go on the next line following the body.

I prefer to put opening braces on the next line like for classes and methods. I guess simply because it looks more symmetrical to me. Funny, but thinking of changing this actually rouses feelings of rebellion. Funny because it would be understandable if I was set in my ways, but my ways have never really been set for any length of time.

I follow most of those formatting conventions as well.

I use tabs as well. Hitting space multiple times just seems silly to me.

Not precisely. The standards are only for the participating projects to adhere to; for interoperability within and between themselves. The group is not setting, or aiming to set, standards for the wider PHP world.


From this (in the PHP Masters article) that didn’t come through, but I’ll trust your take on it.

Here are the first few paragraphs of the article that pointed me to this:

[LEFT][COLOR=#666666][FONT=Georgia][I][FONT=Arial]15[/FONT]| By: [URL=“http://phpmaster.com/author/kthari/”]Hari K T | Posted: May 21, 2012 | [URL=“http://phpmaster.com/category/news-and-opinion/”]News & OpinionReddit482 241 24 Email0

[COLOR=#5F5E5E][FONT=Arial]I hope you all know about the PHP Framework Interoperability Group. The group proposes standards (PSRs) that developers can adhere to in order to make it easier to use their different libraries and frameworks together. The first proposal was [URL=“https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md”]PSR-0 for autoloading class definitions and was a huge success. Recently, the group found it important to address coding standards that should be used in different projects. This proposal was first proposed by [URL=“https://github.com/php-fig/fig-standards/pull/14”]Klaus Silveira and modified heavily by [URL=“http://paul-m-jones.com/”]Paul M Jones after being discussed heavily done in the group’s mailing list.
Of course there were a lot of differences in opinion and the group members fought in a friendly manner to bring about the PSR-1 and PSR-2 proposals. They initially started out as one proposal but the initial round of voting didn’t yield a majority in favor. Participants did however see merit in various requirements the decision was made to split it into 2 proposals — one for mandatory interoperability and one for suggested style.
The voting on PSR-1 and PSR-2 has begun, and they will only be accepted as standards if they get a majority of votes. There are 20 members, and both PSR-1 and PSR-2 have over 11 votes meaning they will soon be accepted as standards. The proposals are:

I appreciate Jones for his time and dedication as a leader to make the PSR. This will help to bring a wonderful future for the PHP community as a whole.


My IDE allows me to set # of spaces assigned to my tab key.

If I want to conform to this I have to change a number of things like my formatting of brackets and the spaces between them. I think I might try to adopt these especially if the larger frameworks and bigger initiatives move this way.


All I can say is that if it didn’t come through, then the article is lacking.

Of course their not. Hidden motives couldn’t be so clear…

Not saying I don’t agree but it is obvious *they have a larger plan.

I tend to follow the conventions set forth by project. Nothing worst than having a cowboy come into a project and changing style for their own self-satisfaction.

The line that does it for me is: “in order to make it easier to use their different libraries and frameworks together”. As I’ve come to understand it, and as that line suggests, the standards are targeted at frameworks, APIs, and libraries. IE: CakePHP, Wordpress, Symfony, etc, in an effort to make them more compatible with each other. It would be hard to influence the entire PHP community to adopt one single “standard”.

I think it would be impossible to influence the entire PHP community. Lone developers and smaller shops will likely use their own standards. Also, not everyone will like the recommendation in these documents.

My question, was meant to ask if developers here have thought about their coding style, and was interested to get some feedback on the PSR-1 Proposal – Basic Coding Standard and [URL=“https://github.com/pmjones/fig-standards/blob/psr-1-style-guide/proposed/PSR-2-advanced.md”]PSR-2 Proposal – Coding Style Guide, and would they use it.

Some smart people put together the Library/framework standards, and it doesn’t hurt for other developers to read about it and form their own opinions about their style.

Like me – this is quite obviously based on K&R, and I thing K&R is stupid, hard to read, and should have been stamped out ages ago.

For starters the excess spaces around assignment and mathematic operators; I always find that harder to read – t o m e t h a t’s l i k e s p a c i n g a s e n t e n c e l i k e t h i s!

For example:
for ($i = 0; $i < 10; $i++) {

I’ve always found hard to follow, can’t tell what’s what; if the spaces were restricted to between statements, and for bitwise comparitors…
for ($i=0; $i<10; $i++) {

It is many times clearer for me – I mean, sure, it’s only four spaces, you wouldn’t think that would make it harder… it sure does for me… again, is everyone else punctuation blind or something? Or is it that for the first decade I did programming not one programming language I used even allowed spaces to be placed in that manner? (or stripped them out after you entered a line)

On the other hand I heartily approve of this

if ($expr1) {
    // if body
} elseif ($expr2) {
    // elseif body
} else {
    // else body;

Putting the opening brace on it’s own like (K&R) I find hard to read, hard to follow, and defeating the point of indenting. Honestly, I think php would be better if it lost the curly braces altogether and simply relied on real words, but I’m a Pascal guy so…

I hate when closing statements don’t line up – and in this case it’s inconsistent with the use of curly braces… how is this:

switch ($expr) {
    case 0:
        echo 'First case, with a break';
    case 1:
        echo 'Second case, which falls through';
        // no break
    case 2:
    case 3:
    case 4:
        echo 'Third case, return instead of break';
        echo 'Default case';

… easy to follow since they all look like drop-throughs? how are the placements of break and return consistent with the use of {} – simple, they aren’t. Consistency certainly is something they never even considered when you look at idiocy like this:

class Foo extends Bar implements FooInterface
    public function sampleFunction($a, $b = null)
        if ($a === $b) {
        } elseif ($a > $b) {
        } else {
            BazClass::bar($arg2, $arg3);

    final public static function bar()
        // method body

Opening brace on same line for operation constructs, but not for classes, methods or functions? A LITTLE CONSISTENCY GUYS!!! Pick a style, not your nose.

That’s my problem with a lot of these types of specs; you can see the design by committee everywhere since there are ZERO clear simple consistent rules. Every time they come to something with another name using the same elements, poof, entirely different way of formatting it.

… and if every case gets a special rule, sorry, that’s not standardization, easy to use, easy to follow, or on the whole worth even TRYING to deal with.

Then there’s all the namespace stuff. I still say if you need that complex a namespace you’ve overthought the solution to your problems – it’s a train wreck of needlessly complex rubbish. In particular, that the namespace uses different delimiters on the filesystem vs. in the program – or even that the program should give a flying purple fish after the code is loaded if said code is actually written properly… I really don’t get why people think that mess is warranted in ANYTHING… but then, I don’t sleaze together off the shelf libraries any-old-way, and disagree with how 99.99% of them work. (probably 100%, I’m just leaving the possibility of there being one that doesn’t SUCK). Hell, it bugs me how PHP passes local scope to includes; there really needs to be a language level include that says do NOT pass scope – that way I’m not doing dumbass functions like:

function safeRequire($file) {
  This is REALLY stupid, but PHP passes local scope to includes -- meaning
  any local variables, even our protected/privates may as well be superglobals
  when you include/require. Wrapping require in a function breaks that scope.

  Remind me to beat the tar out of whoever thought that was a good idea.

But then, I only ever use require_once… I see no legitimate reason for include or non-once to be used since all libraries (includes) should have their code wrapped in classes, methods or functions – that way you can’t blind call them.

Then there’s the “let’s make EVERYTHING use a different naming convention” – which sounds all rosy since if you know the rules you can at a glance tell a class from a method from a function – but it’s also pointlessly difficult to keep track of, and to be frank, if you can’t keep track of:

class myClass {
  function method() {
$class=new myClass;

… in that the word class says it’s a class, saying new means it’s a class, using -> means it’s a variable of type class followed by a property or method, () means it’s a method, lacking it means property… then going to goofy inconsistent naming schemes is NOT going to help you! Again, are people punctuation blind or something?

But too keep it in perspective, what do I know? I think the acid trip of color syntax highlighting is an illegible mess and tabbed editors are a step backwards in functionality!

Still, I find said proposed “standard” to be inconsistent, nonsensical, and almost seeming to be put together willy-nilly. Some parts seem needlessly complex over something simple, some parts seem to be micromanagement of things like directory structures – and not in a good way… and some of it (like brackets and braces) just seems like they want everything to be intentionally random and different to no real advantage.

Hi DeathShadow60,

Some interesting and well thought out arguments!

I did not know about this:

function safeRequire($file) {
This is REALLY stupid, but PHP passes local scope to includes 
-- meaning  any local variables, even our protected/privates may 
as well be superglobals  when you include/require. Wrapping require 
in a function breaks that scope.  

Remind me to beat the tar out of whoever thought that was a good idea.



so thanks for this.


That requireSafe is still not safe because you can use $GLOBALS to still gain access to all global vars. Talking about stupid ideas…

(I mean $GLOBALS, not your function)

It is still a little more safe than not doing it as it helps one side of it?


Yup, that’s true.

I kinda like Yii’s approach to this. The main application is created and run as a singleton, so there are no global variables whatsoever; everything is contained in that main singleton.
Nice and uncluttered :slight_smile:

(not saying it’s the holy grail and that everyone should like it, just saying that I like it :))

I don’t wish to feed the troll but…

The standard did mention one thing about files. Either they are to do some logic (I can’t think of a reason to use this other than output) or are to be class/function definitions etc.

So, let’s look at those types of file:
Output: Generally a template file. Is given variables to use how it wants.
Class/function: does not have interaction with variables declared outside it (apart from in $GLOBALS).

Where do you include these files?
Output: In a method which variables are passed to, designed to be used by the output file.
Class/function: At the top of your file, where they should be, and where many programming languages correctly require you to put them.

If you’re using include() in any way which tampers with variables you don’t want it to (peculiar definition of safe considering such a file was written by the same team), then you’re just using include wrong. Don’t blame the programming language for your misuse of it; Following the standard given makes your ill-named safeRequire function moot.


… and that means you completely MISSED what I posted… globals aren’t the problem; locals being treated as globals is.


class testClass {

  local function test() {
$test=new testClass();


<? echo $this->testValue; ?>

See a problem here? There are a LOT of scenarios where I want to include a file from inside a class, without passing that class’ scope. Hence the function wrapper to break that scope.

I’m not talking about GLOBALS, i’m talking about locals, protected and private’s being treated as locals inside includes since instead of loading code like function libraries, it’s ‘always execute’ instead of deferred.

… and this is an exploitable security hole in several existing CMS and Forums… hit SMF last year, wordpress had a dozen or so back in '08 (contributing to that nice Pwnie award they won). When you want control over what is passed to includes, you’re stuck dropping to the procedural level to do it!

Since when writing a module system for a CMS (for example) you can’t always trust the modules to behave – see how most of the WP vulnerabilities of the past two years are in the mods/plugins and not the system itself! (shades of phpBB2)

I was going to post a big long vitriolic reply to the entire first half of Salathe’s post… but really one sentence to quote and respond to says what I was going to spend several paragraphs on.

Which is no way to write a standard or establish practices; that goes from establishing a standard to simply being documenting practice; to be frank the same type of rubbish as whats contributing to making HTML 5 a steaming pile. It’s why increasingly we should start putting “standard” in quotes and make them in the air with our fingers when using the word. There’s a difference between a standard and what is standard – and it seems people have lost sight of that distinction. Funny since a decade ago we had the opposite problem.

God forbid you have consistent formatting RULES… you set RULES, people obey them; creating rules does NOT mean ‘just pick and choose what’s currently in use’ – because at that point, WHY EVEN BOTHER?!? – it’s already in use…

Ok, first half of the post out of the way… moving on…

Generally no – I’ve tried several, and I come away with that same sour taste in my mouth I get from trying libraries in javascript or CSS. It seems more effort to learn the library, and then work with the library, than to just belt something out from scratch; it certainly seems to result in less code overall and a more predictable result – since such libraries are often ‘black-boxed’ unless you can spend months dissecting them. Don’t tug on that, you don’t know where it’s attached…

It was stupid almost 30 years ago when people were making fat bloated ‘libraries’ for Clipper, Fortran and DiBol, there’s been little improvement since. But again, lessons of the past are soon forgotten.

Or you’re dealing with making a module system where you can’t trust what the end user might add to it (or dealing with a front-end/skinner who’s a total poofta) – a precaution it would seem things like WP or Joomla never even thought of… part of the whole ‘security wholes big enough to sail the USS Iowa through’ to go alongside the other idiocies like storying the mysql UN/PW/host in a DEFINE, multiple entry points with nothing wrapped as if functions and classes are the ultimate evil, etc, etc…


Apparently you’ve never looked at the source code for Magento, phpBB, vBull or Wordpress… since it would seem they’re either unaware of it or don’t care either. It’s just like (again,using a simile so don’t kneejerk into the ‘wah, wah, off topic’ routine) the endless HTML developers who aren’t aware of TH or LABEL (much less fieldset, legend or caption) or the people who brute-force write a md512 instead of calling HASH.

PHP is a massive spec and not everyone is going to know every little detail – ESPECIALLY if they are learning off tutorials instead of reading php.net – even more so when you go to a page about something, and it’s missing important details since such details are under ‘see also’. Though at least PHP is well documented, wish I could say the same for some other languages out there…

A lot of this to me just feels like repeating the mistakes of the past; hardly surprising given all the other lather-rinse-repeat going on in the computing world.


If I did at one time know about the include thing I had long since forgotten. It is more likely that I never read php.net’s documentation for this particular function as I first learned to program PHP from two of the Sitepoint books.

I don’t know many developers who use spaces instead of tabs anyway. Isn’t that just a bit of a waste of filespace?

I could get used to braces on the next line, really. But spaces… yuck.