artbit/isget

这是一个小巧的辅助函数,用于替换常见的模式 isset($a, $a['b']) ? $a['b'] : $c;,这种模式可能显得笨拙且冗余。

v1.0.0 2015-10-24 13:32 UTC

This package is not auto-updated.

Last update: 2024-09-28 16:02:59 UTC


README

Build Status GitHub license GitHub issues

这是一个小巧的辅助函数,用于替换常见的模式 isset($a, $a['b']) ? $a['b'] : $c;,这种模式可能显得笨拙且冗余。

你可以将其视为 isset() 的失散兄弟。

它做两件事

  • 当尝试访问数组中不存在的键时,它将抑制 PHP 未定义索引通知
  • 如果键未设置,则返回默认值

用法

mixed isget(array $inputarray['somekey'], mixed $default_value)

如果 somekey 键已设置,该函数将返回其值,如果没有,则返回提供的默认值(默认为 false);

这在你的函数支持选项数组,且你不想担心检查选项是否已设置时非常有用。例如。

function do_something($required_param, $options = array()) {
    if (isget($options['forceint']) === true) {
        $required_param = intval($required_param);
    }
    if (isget($options['uppercase']) === true) {
        $required_param = strtoupper($required_param);
    }
    ...
    return $required_param;
}
$a = 12.34;
echo do_something($a);
// 12.34
echo do_something($a, array('forceint' => true));
// 12

如果你需要进一步深入,你也可以。

$dream = array();
echo isget($dream['within_a_dream']['within_a_dream']['within_a_dream']['...'], 'inception!');
// inception!

安装

安装此库最简单的方法是使用 Composer,并将以下内容添加到你的项目 composer.json 文件中

{
    "require": {
        "artbit/isget": "dev-master"
    }
}

然后,当你运行 composer install 时,一切都会神奇地就位,并且 isget() 函数将可用于你的项目,只要你包含了 Composer 的自动加载器。

然而,你不需要 Composer 就可以使用这个库。

这个库没有依赖关系,应该在较旧的 PHP 版本上工作。下载代码,并在你的项目中包含 src/isget.php,一切应该都会顺利。