0

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?

1
  • 1
    Perfectly valid: as long as you allow for variable scope, the two shouldn't be in conflict... but an argument isn't a placeholder, it's the variable name that will be used for that argument within the scope of that function Commented Apr 14, 2014 at 21:55

1 Answer 1

2

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 your getAccountID() 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.

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

1 Comment

One reason why the use of global variables is frowned upon

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.