PHP:写入返回值或空值的ISSET函数


php: write isset function which returns value or null

我在项目周围的许多地方(数千个地方)都有以下代码:

$foo = isset($mixed) ? $mixed : null;

其中$mixed可以是任何内容:数组、数组元素、对象、对象属性、标量等。 例如:

$foo = isset($array['element']) ? $array['element'] : null;
$foo = isset($nestedArray['element']['key']) ? $nestedArray['element']['key'] : null;
$foo = isset($object->prop) ? $object->prop : null;
$foo = isset($object->chain->of->props) ? $object->chain->of->props : null;

有没有办法把这个重复的逻辑写成一个(简单的)函数? 例如,我尝试了:

function myIsset($mixed)
{
    return isset($mixed) ? $mixed : null;
}

上面的函数看起来可以工作,但实际上并非如此。 例如,如果$object->prop不存在,并且我调用myIsset($object->prop)),那么我得到致命错误:Undefined property: Object::$prop甚至在调用函数之前。

关于我将如何编写这样一个函数的任何想法? 甚至可能吗?

我意识到这里和这里发布了一些解决方案,但这些解决方案仅适用于阵列。

PHP 7 有一个新的"Null 合并运算符"来做到这一点。是双倍??如:

$foo = $mixed ?? null;

见 http://php.net/manual/en/migration70.new-features.php

我在阅读有关 php 引用时偶然发现了我自己问题的答案。 我的解决方案如下:

function issetValueNull(&$mixed)
{
    return (isset($mixed)) ? $mixed : null;
}

对此函数的调用现在如下所示:

$foo = issetValueNull($array['element']);
$foo = issetValueNull($nestedArray['element']['key']);
$foo = issetValueNull($object->prop);
$foo = issetValueNull($object->chain->of->props);

希望这可以帮助任何寻找类似解决方案的人。

isset是一种

语言结构,而不是常规函数。因此,它可以采用会导致错误的内容,并返回 false。

当您调用 myIsset($object->prop)) 时,将发生评估并收到错误。

见 http://php.net/manual/en/function.isset.php

这与在 JavaScript 中使用 typeof nonExistentVariable 的问题相同。 typeof是一种语言结构,不会导致错误。

但是,如果尝试创建函数,则由于尝试使用未定义的变量而出错。

function isDef(val) {
    return typeof val !== 'undefined';
}
console.log( typeof nonExistent !== 'undefined'); // This is OK, returns false
isDef(nonExistent); // Error nonExistent is not defined

你实际上可以这样写:

$foo = $mixed?:null; 

如果您只想检查它是否存在,请执行此操作

function myIsset($mixed)
{
    return isset($mixed); // this is a boolean so it will return true or false
}
function f(&$v)
{
    $r = null;
    if (isset($v)) {
        $r = $v;
    }
    return $r;
}