【问题标题】:Assigning to an optional reference parameter分配给可选的参考参数
【发布时间】:2014-11-10 13:30:55
【问题描述】:

假设我们定义了一个函数,该函数接受一个包含错误消息的引用参数,但我们并不总是需要错误消息,所以我们允许省略该引用参数:

function isSpider($bug, &$errorMsg = null) {

    if(gettype($bug) !== "object") {
        $errorMsg = "An error occurred: bug must be an object";
        return false;
    }
    return $bug->species === "spider";

}

当我们省略引用参数时,$errorMsg 只是一个局部变量吗?我尝试像上面的示例中那样分配给它,它没有产生带有E_ALL 的错误消息。您可以将默认值分配给一个没有引用的变量,这似乎很奇怪。这很有用,但我只是想确保我理解预期的行为。 PHP 文档对此很吝啬。

可选引用参数允许的两种用例:

// we want to print the error message
if(!isSpider($bug1, $errorMsg)) echo $errorMsg;

或:

// don't care about the error message
if(isSpider($bug)) doSomething();

【问题讨论】:

    标签: php pass-by-reference default-parameters


    【解决方案1】:

    我认为在你的情况下最好使用try-catch 来做错误。

    function isSpider($bug, $alarm=TRUE) {
        if (gettype($bug) !== "object") {
             if ($alarm === TRUE) {
                 throw new Exception("An error occurred: bug must be an object");
             }
             return false;
        }
        return $bug->species === "spider";
    }
    

    如果要打印错误信息:

    try {
        if (isSpider($bug1)) {
            // do something
        }
    } catch (Exception $e) {
        echo "We have an error: ".$e->getMessage();
    }
    

    如果你想保存错误信息以备后用:

    $errorMsg = FALSE;
    try {
        if (isSpider($bug1)) {
            // do something
        }
    } catch (Exception $e) {
        $errorMsg = $e->getMessage();
    }
    
    if ($errorMsg != FALSE) {
        // do something with the error message
    }
    

    如果你想忽略这条消息

    // silent mode
    if (isSpider($bug, FALSE)) {
        // do something
    }
    

    【讨论】:

    • > "您不能在函数中省略引用参数。"这不是真的。来自this page:“注意:从 PHP 5 开始,通过引用传递的参数可能具有默认值。”
    • 哇!我不知道 PHP5 的变化。谢谢:-)
    • 我的方法不会“阻止能够存储错误消息”。我已经更新了我的答案,以展示你是如何做到的。
    • Np。它在文档中只简要提到过一次,所以如果一堆人不知道它,我不会感到惊讶。
    • 啊,你是对的。我第一次误解了你的例子。感谢更新。 [不小心删除了我之前的评论。]
    猜你喜欢
    • 2022-06-15
    • 1970-01-01
    • 2011-01-08
    • 1970-01-01
    • 2019-07-20
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    相关资源
    最近更新 更多