1

I have a PHP function:

function unserialize_recursive($data, $i = 0) {

    $unserialized = unserialize($data);

    if ($unserialized) {
        $i++;
    }

    if (!is_string($unserialized) || unserialize($unserialized) === FALSE) {
        /* placeholder - see explanation below */
        return array($i, $unserialized);
    } elseif (unserialize($unserialized) !== FALSE) {
        unserialize_recursive($unserialized, $i);
    }
    return FALSE;
}

I call this function with:

$data = unserialize_recursive($serialized_string);
var_dump($data);

But the output of var_dump($data) is bool(false).

However, if I add var_dump($unserialized) in the position of the text /* placeholder - see explanation below */, I get the expected output.

So why can I not return that variable ($unserialized)? If I use gettype() on it at that point in the function, it returns array.

I'm using Netbeans and all the syntax highlighting indicates the code is properly formed with no typos. I'm baffled. Have I missed something really obvious?

4

3 回答 3

2

我的猜测是你忘记了回报:

function unserialize_recursive($data, $i = 0) {

$unserialized = unserialize($data);

if ($unserialized) {
    $i++;
}

if (!is_string($unserialized) || unserialize($unserialized) === FALSE) {
    /* placeholder - see explanation below */
    return array($i, $unserialized);
} elseif (unserialize($unserialized) !== FALSE) {
    return unserialize_recursive($unserialized, $i);
}
return FALSE;
}
于 2013-04-28T20:12:41.270 回答
1

您在函数中使用递归。

因此,您的 var_dump($unserialized) 是从递归调用中调用的,但主调用返回 false。

您可能需要更改“unserialize_recursive($unserialized, $i);” 至

return unserialize_recursive($unserialized, $i);
于 2013-04-28T20:15:19.890 回答
0

你在前面缺少回报

unserialize_recursive($unserialized, $i);

所以应该是这样的

返回unserialize_recursive($unserialized, $i);

如果没有返回函数,它会自行运行,然后离开 if 条件并执行 return FALSE。通过将 return 放在前面,您可以结束当前函数并启动另一个函数。

于 2013-04-28T20:17:48.720 回答