PHP array vs [ ] in method and variable declaratio

2019-02-05 11:14发布

问题:

I have a small symantic question.

When defining functions and variable, 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 = []){}

回答1:

PSR-2 (by PHP Framework Interoperability Group) does 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.



回答2:

from PHP docs:

As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].

<?php
$array = array(
    "foo" => "bar",
    "bar" => "foo",
);

// as of PHP 5.4
$array = [
    "foo" => "bar",
    "bar" => "foo",
];
?>

if you'd try using '[]' notation in earlier version than 5.4, it will fail, and PHP will throw a syntax error

for backward-compatibility you should use array() syntax.



回答3:

That depends on what version of PHP you are targeting. For the best backward compatibility, I'd recommend you to use array(). If you don't care about older versions (< PHP 5.4), I'd recommend you to use a shorter version.



标签: php standards