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 = []){}
In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.
The ONLY difference between [] and array() is syntactic, since [] is an abbreviation for array().
Unless you like notices about undeclared variables, I would recommend to initialize. Plus, it just makes for legible code (it's clear that $foo = array() and that it wasn't a string turned in to an array, etc.).
To create an array, you use the array() construct: $myArray = array( values ); To create an indexed array, just list the array values inside the parentheses, separated by commas.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With