array_push() 实际需要多少个参数? [英] How many parameters does array_push() actually expect?

查看:26
本文介绍了array_push() 实际需要多少个参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://php.net/manual/en/function.array-push.php 清楚地显示了函数的签名,可变参数是完全可选的:

http://php.net/manual/en/function.array-push.php clearly shows the signature of the function with the variadic being completely optional:

int array_push ( array &$array [, mixed $... ] )

我认为,当将 array_push 与 splat 运算符一起使用时,非常希望它接受空的可变参数,例如允许这样的代码:

I think that, when using array_push with splat operator, it would be extremely desired for it to accept empty variadic, e.g. to allow such code:

<?php

function add( array $arr1, array $arr2 ) {
    return \array_push($arr1, ...$arr2);
}

echo add(['foo'], ['bar']); // OK, returns 2
echo add(['foo'], []); // should be OK, but ain't currently - raises an E_WARNING
?>

出于这个确切原因,许多语言(例如 Java)允许函数中的空变量(通常导致无操作).PHP 没有,至少在 PHP 7.1 和 7.2 中没有.

Many languages (e.g. Java) allow empty variadics in functions (usually resulting in a no-op) for that exact reason. PHP doesn't, at least not in PHP 7.1 nor 7.2.

OTOH,虽然共享相似的语法定义,array_merge 和许多其他接受空变量并使用上述 splat 语法正常工作:

OTOH, although sharing a similar syntax definition, array_merge and many other accept the empty variadic and work correctly using the aformentioned splat syntax:

var_dump( array_merge(['foo'], ...[]) ); // works for me.

我的问题是:

  1. 这实际上是预期行为和文档错误、实现中的错误还是其他原因?
  2. (a) 如果这是一种有意的行为,根据上述情况,其背后的基本原理是什么?
  3. (b) 如果这是一个错误,为什么会发生?

注意:我已经检查了其他数组函数的文档,例如http://php.net/manual/en/function.compact.php, http://php.net/manual/en/function.array-merge.php 等完全按照预期显示参数列表).

note: I've checked the docs for other array functions, and e.g. http://php.net/manual/en/function.compact.php, http://php.net/manual/en/function.array-merge.php etc. show the param list exactly as expected).

推荐答案

好吧,这个巨大的谜团似乎已经解决了:在查看 https://github.com/php/php-src/blob/master/ext/standard/array.c,我为 array_push 找到了这个:

Well, the great mystery seems to be solved: while poking through the commits in https://github.com/php/php-src/blob/master/ext/standard/array.c, I found this for array_push:

ZEND_PARSE_PARAMETERS_START(1, -1)
    Z_PARAM_ARRAY_EX(stack, 0, 1)
    Z_PARAM_VARIADIC('+', args, argc)
ZEND_PARSE_PARAMETERS_END();

最近从 ZEND_PARSE_PARAMETERS_START(2, -1) 更改了第一行,使问题不存在.

The first line was changed recently, from ZEND_PARSE_PARAMETERS_START(2, -1), making the issue nonexistent.

https://github.com/php/php-src/commit/f7f48643e779111b23b546689b9fbb4e3affe1e7"

引用:

php-7.3.0alpha1

array_push() 和 array_unshift() 现在也可以用单个参数调用,这特别方便.展开运算符.

array_push() and array_unshift() can now also be called with a single argument, which is particularly convenient wrt. the spread operator.

这似乎既是文档错误又是功能缺失.是的,PHP 7.3 开发人员实现了这一点!

It seems it was both a documentation error and a missing feature. Yay for PHP 7.3 devs for implementing this!

这篇关于array_push() 实际需要多少个参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆