本文介绍了在 PHP 中初始化(空)数组的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些其他语言(例如 AS3)中,已经注意到如果像这样初始化一个新数组会更快 var foo = [] 而不是 var foo = new Array() 出于对象创建和实例化的原因.我想知道 PHP 中是否有任何等价物?

In certain other languages (AS3 for example), it has been noted that initializing a new array is faster if done like this var foo = [] rather than var foo = new Array() for reasons of object creation and instantiation. I wonder whether there are any equivalences in PHP?

class Foo {
    private $arr = array(); // is there another / better way?
}

推荐答案

在 ECMAScript 实现(例如 ActionScript 或 JavaScript)中,Array() 是构造函数,[] 是数组文字语法的一部分.两者都以完全不同的方式优化和执行,文字语法不受调用函数的开销的影响.

In ECMAScript implementations (for instance, ActionScript or JavaScript), Array() is a constructor function and [] is part of the array literal grammar. Both are optimized and executed in completely different ways, with the literal grammar not being dogged by the overhead of calling a function.

另一方面,PHP 的语言结构可能看起来像函数,但实际上并不如此.即使使用支持 [] 作为替代方案的 PHP 5.4,在开销上也没有区别,因为就编译器/解析器而言,它们完全是同义词.

PHP, on the other hand, has language constructs that may look like functions but aren't treated as such. Even with PHP 5.4, which supports [] as an alternative, there is no difference in overhead because, as far as the compiler/parser is concerned, they are completely synonymous.

// Before 5.4, you could only write
$array = array(
    "foo" => "bar",
    "bar" => "foo",
);

// As of PHP 5.4, the following is synonymous with the above
$array = [
    "foo" => "bar",
    "bar" => "foo",
];

如果您需要支持旧版本的 PHP,请使用以前的语法.还有一个关于可读性的争论,但作为一个长期的 JS 开发人员,后者对我来说似乎很自然.在我第一次学习 PHP 时,我实际上犯了一个错误,尝试使用 [] 初始化数组.

If you need to support older versions of PHP, use the former syntax. There's also an argument for readability but, being a long-time JS developer, the latter seems rather natural to me.  I actually made the mistake of trying to initialise arrays using [] when I was first learning PHP.

这个对语言的更改最初是提议的,但由于核心的多数票反对而被拒绝开发者的原因如下:

This change to the language was originally proposed and rejected due to a majority vote against by core developers with the following reason:

这个补丁不会被接受,因为核心开发者的微弱多数投了反对票.但是,如果您在核心开发人员和用户投票之间采取累积平均值似乎表明相反,那么提交补丁从长远来看不受支持或维护是不负责任的.

但是,似乎在 5.4 之前发生了变化,这可能是受到了对流行数据库(如 MongoDB(使用 ECMAScript 语法)的支持)的实现的影响.

However, it appears there was a change of heart leading up to 5.4, perhaps influenced by the implementations of support for popular databases like MongoDB (which use ECMAScript syntax).

这篇关于在 PHP 中初始化(空)数组的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 00:14