Search code examples
phpstandards

PHP array vs [ ] in method and variable declaration


I have a question about PHP syntax.

When defining functions and variables, which convention should I use?

I know they do the same thing in practice but I would like to know which method conforms to best practice standards.

Variables

public $varname = array();

or

public $varname = [];

Methods

public function foo($bar = array()){}

or

public function foo($bar = []){}

Solution

  • PSR-2 and PSR-12 (by PHP Framework Interoperability Group) do not mention short array syntax. But as you can see in chapter 4.3 they use short array syntax to set the default value of $arg3 to be an empty array.

    So for PHP >= 5.4 the short array syntax seems to be the de-facto standard. Only use array(), if you want your script to run on PHP <5.4.