当前位置: 动力学知识库 > 问答 > 编程问答 >

Is it bad practice to use reference assignment in PHP when handling potentially undefined variables?

问题描述:

I've been thinking of using reference assignment as a shortcut for dealing with potentially undefined variables.

In other words, instead of:

$foo = isset($this->blah['something']['else']) ? $this->blah['something']['else'] : null;

if (!is_null($foo) && ...){

//do something with $foo

}

I could do this:

$foo = &$this->blah['something']['else'];

if (!is_null($foo) && ...){

//do something with $foo

}

Seems simpler, right? Because of the way PHP handles assignment by reference, I don't have to worry about $this->blah['something']['else'] being defined, because if it doesn't exist it will be created automatically and set to NULL.

Is this strategy frowned upon?

网友答案:

If you just want to test if a variable is set and not null, then you better test:

if (! empty($this->blah['something']['else'])) {...}

This way you avoid creating two references to a value that could not even exist.

In my opinion, every time you create a new reference to the same value, your code becomes harder to understand at a glance.

If you need zero as non-empty, then you better create a global function like this:

function eempty(& $var) {
  return empty($var) && $var !== 0;
}
网友答案:

I personally think it could be more conventional, but assigning a referred value like that seems a bit redundant to me. I'd just stick with the more commonly used ternary operator in your situation. Often it's a lot clearer to understand. Of course, you should follow your personal semantics as close as possible.

分享给朋友:
您可能感兴趣的文章:
随机阅读: