PHP可选函数参数与数组.如何编码/更好的代码方式?

Ros*_*oss 7 php web-applications

我相信这会更好.任何帮助将不胜感激.

我想将一个数组传递给包含参数的php函数,所有参数都是可选的.我正在使用代码点火器,绝不是专家.以下是我到目前为止使用的内容:

function addLinkPost($postDetailArray) {

    if (isset($postDetailArray['title'])) {
        $title = $postDetailArray['title']; }
    else {
        $title = "Error: No Title";
    }

    if (isset($postDetailArray['url'])) {
        $url        = $postDetailArray['url'];
    } else {
        $url        = "no url";
    }
    if (isset($postDetailArray['caption'])) {
        $caption    = $postDetailArray['caption'];
    } else {
        $caption    = "";
    }
    if (isset($postDetailArray['publish'])) {
        $publish    = $postDetailArray['publish'];
    } else {
        $publish    = TRUE;
    }
    if (isset($postDetailArray['postdate'])) {
        $postdate   = $postDetailArray['postdate'];
    } else {
        $postdate   = "NOW()";
    }
    if (isset($postDetailArray['tagString'])) {
        $tagString  = $postDetailArray['tagString'];
    } else {
        $tagString = "";
    }
Run Code Online (Sandbox Code Playgroud)

Ion*_*tan 27

您可以使用默认值数组,然后将参数数组与默认值合并.如果它们出现在参数数组中,则将覆盖默认值.一个简单的例子:

$defaults = array(
    'foo' => 'aaa',
    'bar' => 'bbb',
    'baz' => 'ccc',
);

$options = array(
    'foo' => 'ddd',
);


$merged = array_merge($defaults, $options);

print_r($merged);

/*

Array
(
    [foo] => ddd
    [bar] => bbb
    [baz] => ccc
)

*/
Run Code Online (Sandbox Code Playgroud)

在你的情况下,那将是:

function addLinkPost($postDetailArray) {
    static $defaults = array(
        'title'     => 'Error: No Title',
        'url'       => 'no url',
        'caption'   => '',
        'publish'   => true,
        'postdate'  => 'NOW()',
        'tagString' => '',
    );

    $merged = array_merge($defaults, $postDetailArray);

    $title     = $merged['title'];
    $url       = $merged['url'];
    $caption   = $merged['caption'];
    $publish   = $merged['publish'];
    $postdate  = $merged['postdate'];
    $tagString = $merged['$tagString'];
}
Run Code Online (Sandbox Code Playgroud)


Ins*_*ire 10

你可以这样做:

function addLinkPost(array $postDetailArray)
{
    $fields = array(
        'key' => 'default value',
        'title' => 'Error: No Title',
    );

    foreach ($fields as $key => $default) {
        $$key = isset($postDetailArray[$key]) ? $postDetailArray[$key] : $default;
    }
}
Run Code Online (Sandbox Code Playgroud)

只需使用您的密钥及其默认值编辑$ fields数组.