使用相同的名称将变量传递给函数

使用相同的名称将变量传递给函数

问题描述:

Is it considered wrong to pass a variable to a function where the variable passed has the same name as the variable in the function itself? I never see anyone do this, but wondered if there was a reason why (other than readability). Example:

$variable = "value";

function myFunction($variable) {
    return $variable;
}

将变量传递给传递的变量与变量中的变量同名的函数是否被认为是错误的 功能本身? 我从来没有看到有人这样做,但想知道是否有原因(除了可读性)。 示例: p>

  $ variable =“value”; 
 
function myFunction($ variable){
 return $ variable; 
} 
  code>   pre> 
  div>

No there is not problem with doing this except some naming confusion. Because,

$variable = "value"; // this declaration belong to a global scope

// but $variable passing through as argument, makes it scope within that function declaration only
function myFunction($variable) {
    return $variable;
}

You might have expect that if you call the function like myFunction() i.e. without any parameter, it will return you "value", but absolutely not, cause $variable passed as argument is not the global one.

But if you try to use the global $variable within the myFunction, then it will cause some conflict, that is why no one do this.

Aside from making variables a bit confusing to track, there is nothing wrong with this. They exist in different scopes.

You can use global and add default value in param variable.

$variable = "value";
function myFunction($variable = '') {
        global $variable;
    return $variable;
}

It is up to you but vice versa, if you want to pass intentionally a variable into a function.. then you have to use this:

$variable = "value";

function myFunction($variable) {
global $variable;
return $variable;
}

echo myFunction('another value');

One more point. When creating functions you may set a default value for your params to avoid errors:

function myFunction($variable="default value") {
return $variable;
}

echo myFunction();

There is nothing wrong with it at all, and I would have thought it's quite common.

However, you should always be choosing the best name for a variable, or a parameter, in each situation, not applying one rule to your whole code.

For instance, in a database lookup function, it might be obvious what $id refers to, so it would be a sensible parameter name; but where you are calling it, you will likely have lots of IDs of various sorts, so a more descriptive variable name should be used. On the other hand, each time you build an SQL string, it's probably the only such variable in scope, so giving it a consistent name keeps your code tidy and easy to read.

A common observation is that all code is read more often than it is written (yes, even your personal website that you wouldn't dare share with the world). Variable names should be chosen with that in mind: what makes this code easy to read, understand, and maintain?