开发者

Which is the better way to reference a variable outside the function scope?

I can change $var in my function in one of two ways: either pass it by reference or using the global keyword.

$var1 = 10;

function test1() {
    global $var1;
    $var1++;
}

function test2(&$var) {
    $var++;
}

Both approaches have the same result, but is there any difference bet开发者_StackOverflow中文版ween them? Which one is preferred and which one is faster?


1. None of them is preferred.

Unless you have a special reason to do otherwise, the preferred would be

$var1 = 10;
$var1 = test3($var1);
function test3($var)
{
    return $var + 1;
}

Introducing coupling between different parts of your program (if using a global) is something you should always reasonably try to avoid.

In addition, if there is no concrete reason to make your function accept its argument by reference you should also avoid doing that. Only a very miniscule fraction of all functions behave this way, so if nothing else you are risking confusion among the developers who use this code for no real benefit.

2. You do not need to think about which one is faster.

Unless you have profiled your application under real world scenarios and have found that this function is a bottleneck (which of course it will never be in this simple form), then optimizing for performance at the expense of writing clear and maintainable code is not only pointless, but also detrimental.

As a bonus, I should mention that using a reference might actually make the function slower.


Since global variables pollute the namespace (i.e. can be used inadvertently and/or by another function with the same idea), references are preferable.

However, in many cases (where the data structures are more complex), you should be using objects instead, like this:

class Counter {
  private $val = 10;
  public function increment() {
    $this->val++;
  }
}

The speed of any of these solutions does not matter and will be dwarfed by any actual computation.


Preferred way is avoiding globals. The reason is that if you put a variable in global scope, you lose control over it - since projects grow, you might forget what the name of your global variable is and you can overwrite it accidentally somewhere causing an incredible headache for yourself.

From performance point of view - reference is faster and it's also much safer to use because you define in method's signature whether a reference is being used or not, making the actual function call easy as you don't have to pass the variable by reference explicitly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜