Someone please explain to me why this doesn’t work, and what I am doing wrong. For some reason, when I run the function validateUsername, the $error variable remains completely unchanged, instead of evaluating to true. How is this possible?
Yet, if I remove the code within the function and run it straight without a function call, it works. The example below is so simple it is practically pseudo code, and yet it doesn’t work. Is this behavior unique to PHP? I don’t want to run into this again in some other language.
<?php
$username = 'danielcarvalho';
$error = false;
function validateUsername()
{
if (strlen($username) > 10)
{
$error = true;
}
}
validateUsername();
if ($error == false)
{
echo 'Success.';
}
else
{
echo 'Failure.';
}
?>
This isn’t working because
$usernameisn’t available within the scope of yourvalidateUsernamefunction. (Neither is the$errorvariable.) See the variable scope section of the PHP manual for more information.You could fix this by adding
global $username, $error;within your function, although this isn’t a particularly elegant approach, as global variables are shunned for reasons too detailed to go into here. As such, it would be better to accept$usernameas an argument to your function as follows: