PHP: can variables and arguments get mixed up if they share the same name?
There are 2 places where $account_name occurs in my code, one where is the name of an argument of a function:
functions.php:
function getAccountID ($account_name) {
$account_id = mysql_query("SELECT account_id FROM accounts WHERE account_name = '$account_name'");
$account_id = (mysql_fetch_assoc($account_id));
}
and the other where it is a variable with a value
index.php:
$account_name = $fileop[0];
$account_id = getAccountID($account_name);
I am aware that the two instances of the variable have completely separate uses: the first is just a placeholder for the function to take an argument, and the second carries a value outside the function's scope. I am trying to simplify things as much as possible which is why I would like them to be the same. Does this work and if so is it acceptable practice?
Answer
Solution:
Take a look at understanding the PHP variable scope.
In short, yes is this possible, and there are no real issues with convention as long as the name is descriptive of what it contains. It is very common practice to reuse variable names between functions as long as there is no confusion about what they might represent.
The exception to this is if
$account_name
were to be a global variable, which could be accessible anywhere in the code, including in yourgetAccountID()
function. If this were the case, then reusing the variable name would cause execution issues or errors, or at the very least, make your code difficult to understand.