PHP array vs [ ] in method and variable declaration

时光毁灭记忆、已成空白 提交于 2019-12-29 04:05:29

问题


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 = []){}

回答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.




回答4:


just made a test to see how [] performs vs array() here is what I got

testing 1 million []s ( with $arr[] = [] )
started at : 1561298821.8754
ended at: 1561298822.6881
difference: 0.81266021728516 seconds 

testing 1 million array()s ( with array_push( $arr, array()) )
started at : 1561298822.6881
ended at: 1561298823.843
difference: 1.1549289226532 seconds 

testing 1 million []s ( again while the processor is hotter)
started at : 1561298823.8431
ended at: 1561298824.7448
difference: 0.9017219543457 seconds 

so [] performed about 20% faster



来源:https://stackoverflow.com/questions/26651996/php-array-vs-in-method-and-variable-declaration

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!