PHP - 我是否正确调用函数?

Here is my code:

$oldPhone = $_POST["phone"];

$newPhone = makeInteger($oldPhone);

lengthMustBe($newPhone, 10, "Please enter a valid 10-digit phone number.");

Here is the function:

function lengthMustBe($str, $length, $errormsg) {

    if (strlen($str) != $length) {
        $status = "failure";
        $error = $errormsg;
    }

};

The function is pretty self explanatory..

When I try to pass it "123", 10, "Not long enough", $status is still "success" (defined at top of page.)

you need to set the $status variable like:

$tmpArray = lengthMustBe($newPhone, 10, "Please enter a valid 10-digit phone number.");
$status = $tmpArray[0];
$statusMsg = $tmpArray[1];

and your function:

function lengthMustBe($str, $length, $errormsg) {

    if (strlen($str) != $length) {

        return array("failure", $errormsg);
    }
    else
    {
        return array("success", "");
    }
}

don't use globals its just a terrible idea...

How is $status defined at the top of the page? My guess is the scope of $status in this function makes it a different variable then the one defined at the top of the page.

I think $status is not global... meaning it'll only be "failure" within that function, but when you try to call it from elsewhere, the global $status is called - which has been defined as "success" at the top of the page.

http://php.net/manual/en/language.variables.scope.php

The scope of $status var is inside the function lengthMustBe.

You can define $status as a global var like this :

function lengthMustBe($str, $length, $errormsg) {
    global $status;
    // ...