0

I'm trying to write a function which appends a string to an existing string for error handling.

The output that I'm searching:

// Begin:
// message1
// message2


Currently I have:

$error = "Begin:";

function addError($message) {
    $error .= "<br>" . $message;
}

addError("message1");
addError("message2");

echo $error;

// ----- Which outputs -----
// Begin:


I would assume that the code above does the same as:

$error = "Begin:";

$error .= "<br>" . "message1";
$error .= "<br>" . "message2";

echo $error;

// ----- Which outputs -----
// Begin:
// message1
// message2


But it doesn't seem to work. Could someone elaborate on the mistake(s) I'm making?

1
  • 4
    The $error variable inside the function is not the $error variable you used outside. Take a look at Variable scope. Commented Apr 17, 2020 at 18:51

1 Answer 1

1
function addError($message) {
    $error .= "<br>" . $message;
}

The error variable only exist in the function's scope.

You could pass the error variable as a reference to the function, described with the & sign.

$error = "Begin:";

function addError(&$error, $message) {
    $error .= "<br>" . $message;
}

addError($error, "message1");
addError($error, "message2");

echo $error;

Test online!


On other option would be defining and changing a global variable.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.