分配给可选的参考参数

Say we have define a function that takes a reference paramter which will contain an error message, but we don't always need the error message, so we allow that reference parameter to be omitted:

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

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

}

When we omit the reference parameter, is $errorMsg just a local variable? I tried assigning to it like in the example above and it produced no error messages with E_ALL on. It seems strange that you can assign a default value to a variable that is a reference to nothing. It's useful, but I just want to make sure I understand the intended behavior. The PHP docs are skimpy on this.

The two use cases that the optional reference parameter permits:

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

or:

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

I think its better use try-catch to do error in your case.

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

If you want to print the error message:

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

If you want to store the error message for later use:

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

if ($errorMsg != FALSE) {
    // do something with the error message
}

And if you want to ignore the message

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