开发者

PHP: What's the difference between initializing an array with "new" vs without it?

开发者 https://www.devze.com 2023-01-25 04:28 出处:网络
I\'ve always created arrays by just populating them $foo[] = \'开发者_如何转开发car\'; but I\'ve seen a lot of

I've always created arrays by just populating them

$foo[] = '开发者_如何转开发car';

but I've seen a lot of

$foo = array();
$foo[] = 'car';

and

$foo = new array();

What's the difference between not initializing, using array(), and using new array();?

thanks!


You don't instantiate an array in PHP using:

$foo=new array(); // error in PHP

That's for Javascript:

foo=new Array(); // no error in Javascript

In PHP, new is used only for instantiating objects.


The difference is that using new does not work, since array() is a language construct and not an object constructor. It throws an error:

Parse error: syntax error, unexpected T_ARRAY in php shell code on line 1

On the other hand, declaring it like

$f=array();

before you start assigning items is a good practice. Strict error reporting mode may give a warning about using an undeclared variable otherwise.


You are able to instantiate an array in PHP using the new keyword, however it's a little bulkier than arrays created using the array() function, and does not use the same call.

new ArrayObject();

will instantiate an array as an object. More importantly this is an extensible class, should you want to use array syntax with an object in object oriented PHP. In most cases it's advisable just to use array() for speed and simplicity.

Edit: i guess I never actually answered the question.

$var = array();
$var[] = 'car';

will make a new empty array and then append 'car' to the array. It's good form to initialize any and all arrays. It would be better to write these two lines as one: $var = array('car');

$var[] = 'car';

will make a new array with 'car' in it if $var is not an array or is empty. If $var happens to have already been declared as array, you might find that you've accidentally kept some older values (which is why it's good form to initialize your arrays).

$var = new ArrayObject();
$var[] = 'car';

is the OOP way to declare an array. It's a bit more resource intensive, so stick with array() unless you have a good reason to use ArrayObject

Note:

Incrementing an uninitialized numeric variable is significantly slower than incrementing an initialized numeric variable ($i++ is slower than $i = 0; $i++). This is not the case for arrays in php: ($var[] = 'car' is approximately the same as $var = array(); $var[] = 'car')


foo = new Array(); is javascript syntax.

It is good practice to pre-initialize your arrays when applicable so you don't accidentally populate data to an existing array with the same name defined elsewhere in the code.

0

精彩评论

暂无评论...
验证码 换一张
取 消