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?

  • 4
    The `$error` variable inside the function is not the `$error` variable you used outside. Take a look at [Variable scope](https://www.php.net/manual/en/language.variables.scope.php). – Aioros Apr 17 '20 at 18:51

1 Answers1

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.
0stone0
  • 34,288
  • 4
  • 39
  • 64