PHP 函数参数 - 是否使用数组? [英] PHP Function Arguments - Use an array or not?

查看:20
本文介绍了PHP 函数参数 - 是否使用数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢使用键=> 值对(数组)作为参数而不是单个参数来创建我的 PHP 函数.

I like creating my PHP functions using key=>value pairs (arrays) as arguments instead of individual parameters.

例如,我更喜欢:

function useless_func($params) {
    if (!isset($params['text'])) { $params['text'] = "default text"; }     
    if (!isset($params['text2'])) { $params['text2'] = "default text2"; }   
    if (!isset($params['text3'])) { $params['text3'] = "default text3"; }   
    echo $params['text'].$params['text2'].$params['text3'];
    return;
}

我不喜欢:

function useless_func($text = "default text", $text2 = "default text2", $text3 = "default text3") {
        echo $text.$text2.$text3;
    return;
}

我第一次看到在 Wordpress 代码库中广泛使用这种方式.

I had first seen things done this way extensively in the Wordpress codebase.

我更喜欢数组的原因:

  • 可以按任意顺序提供函数参数
  • 更容易阅读代码/更多的自我记录(在我看来)
  • 不易出错,因为在调用函数时我必须调查正确的数组键

我和一位同事讨论过这个问题,他说这没用,只会导致额外的代码,而且设置默认值要困难得多.基本上,他在所有三点上都完全不同意我的观点.

I was discussing this with a co-worker and he says that it's useless and just leads to extra code and it's much harder to set the default values. Basically, he disagrees with me completely on all three points.

我正在寻求专家的一些一般性建议和指导,他们可能能够提供见解:这样做的更好或更正确的方法是什么?

I am looking for some general advise and guidance from experts who might be able to provide insight: What's the better or more proper way to do this?

推荐答案

嗯,有点用.但是对于某些总是传递的参数,最好使用经典传递,例如 function some($a1, $a2).我在我的代码中这样做:

Well, it's kinda usefully. But for some arguments which is passing always it's better to use classic passing like function some($a1, $a2). I'm doing like this in my code:

function getSome(SomeClass $object, array $options = array())
{
    // $object is required to be an instance of SomeClass, and there's no need to get element by key, then check if it's an object and it's an instance of SomeClass

    // Set defaults for all passed options
    $options = array_merge(array(
        'property1' => 'default1',
        'property2' => 'default2',
        ... => ...
    ), $options); 
}

所以,正如你所看到的,我也喜欢这种代码风格,但对于核心参数我更喜欢经典风格,因为这样 PHP 控制了更多的东西,如果我使用你的代码风格.

So, as you can see I like that code style too, but for core-arguments I prefer classic style, because that way PHP controls more things which should I, if I used the you code style.

这篇关于PHP 函数参数 - 是否使用数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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