带数组的 PHP 可选函数参数.如何编码/更好的编码方式? [英] PHP optional function arguments with array. How to code / Better way to code?

查看:26
本文介绍了带数组的 PHP 可选函数参数.如何编码/更好的编码方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm sure there is a better to this. Any help will be greatly appreciated.

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

I want to pass an array to a php function that contains the argument and all the arguments are optional. I'm using code ignitor and am by no means an expert. Below is what i have been using so far:

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 = "";
    }

推荐答案

你可以这样做:

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;
    }
}

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

Simply edit the $fields array with your key and its default value.

这篇关于带数组的 PHP 可选函数参数.如何编码/更好的编码方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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