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:


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


$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?




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.

People are also looking for solutions to the problem: php - How to set "ORDER BY" for two cases?


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.