#34 Reformatting Source Code

code, refactoring, formatting, style

Reformatting Source Code

PhpStorm can help ensure your code adheres to whichever coding standard you follow. Press Cmd+Alt+L (Ctrl+Alt+L on Windows/Linux) to reformat the source code for the current selection or the entire file if nothing is selected.

Be sure to configure your preferred code style in the preferences, the example above is set to use the PSR2 standard. You can easily configure PhpStorm to use the PSR1/2 standards by going to Editor | Code Style | PHP in the preferences and clicking on Set from... | Predefined Style | PSR1/PSR2.

It's not that easy to see what's changed in the example above so I'll include it down here. The starting code did not follow PSR2 standards and looked like this:

class Example {
    public function __construct() {
        $array = array(1,2,3);
        if (count($array) > 3)
        {
            foreach ($array as $item)
                echo $item;
        }
    }
}

It was then reformatted to conform to the PSR2 standard and looked like this:

class Example
{
    public function __construct()
    {
        $array = [1,2,3];
        if (count($array) > 3) {
            foreach ($array as $item) {
                echo $item;
            }
        }
    }
}

Further Reading

Related Tips

Blog Comments powered by Disqus.