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

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

问题描述

我喜欢使用key => value对(数组)作为参数而不是单个参数来创建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天全站免登陆