gpt4 book ai didi

PHP:函数将大量数组作为参数传递

转载 作者:行者123 更新时间:2023-12-02 01:13:45 25 4
gpt4 key购买 nike

我需要创建一个函数,其中有大量参数可以为 null 或值。现在我正在创建如下示例的函数:

function container($args){

$args += array(
'limit' => 10,
'container' => null,
'container_class' => null,
'list_class' => null,
);

echo'<'.$args['container'].' class="'.$args['container_class'].'" >';

echo 'My function will have other content here with the '.$args['limit'];

echo '<ul class="'.$args['list_class'].'" >';
echo '<li>list itme here</li>';
echo '</ul>'

echo '</'.$container.'>';

}

如果我必须在数组中传递 4-5 个值,这很好,但如果我有超过 15-20 个键要传递怎么办?必须有一些适当的方式来实现。

那么我怎样才能以如此有效的方式创建一个函数来传递许多数组键作为参数呢?

非常感谢

最佳答案

15-20 个键并不是一个很大的数组。当您需要考虑如何将某些内容传递给 args 时,就是当您拥有 1000 多个键时。

无论如何你都可以使用“按引用传递”的概念(参见 http://php.net/manual/en/language.references.pass.php )。当您必须在没有任何返回语句的情况下将变量修改为函数时,这个概念很有用。但是为了实现这个目标,PHP 不发送变量的副本,而是发送一个引用内存中变量的键。

并且这个键不依赖于变量的大小。

如何使用?通过在函数声明中使用 & 符号例如:

function container(&$args) 
{
// your function
}

$args = array(1, 2, 3 ..., 100000);
container($args);

但是,如果您使用“通过引用传递”概念,请注意不要修改 $args,否则 $args 将在主脚本中被修改。

Final world:如果您的 key 少于 50 个,则不关心如何传递您的参数,只需复制使用(默认行为)会更安全!

关于PHP:函数将大量数组作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14291694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com