取消设置变量,而不检查变量是否已被使用或声明

问题描述:

To unset a variable without cheking whether it has been already used or declared.Which is valid in PHP: (a) or (b)? Although both works. In the sample code below,forward referencing is used,how PHP handles it internally?

(a)

while(stmt1->fetch())
{
   unset($data);
   $i=0;
   while(stmt2->fetch())
   {
     //Some code.......
     $data[$i] = $some_Value;
     $i++;
   }
}

(b)

while(stmt1->fetch())
{
   if(isset($data))
   {
     unset($data);
   }
   $i=0;
   while(stmt2->fetch())
   {
     //Some code.......
     $data[$i] = $some_Value;
     $i++;
   }
}

取消设置变量而不检查它是否已被使用或声明。它在PHP中是否有效:(a) 或(b)? 虽然两者都有效。 在下面的示例代码中,使用了正向引用,PHP如何在内部处理它?

(a) p>

  while(stmt1-&gt  ; fetch())
 {
 unset($ data); 
 $ i = 0; 
 while(stmt2-> fetch())
 {
 //一些代码......  。
 $ data [$ i] = $ some_Value; 
 $ i ++; 
} 
} 
  code>  pre> 
 
 

(b) p>

  while(stmt1-> fetch())
 {
 if if(isset($ data))
 {
 unset($ data); 
} 
 $ i =  0; 
 while(stmt2-> fetch())
 {
 //一些代码....... 
 $ data [$ i] = $ some_Value; 
 $ i ++; 
}  
} 
  code>  pre> 
  div>

Instead of unsetting the variable, set it with an initial value. This conveys the intention much clearer.

Also, you don't need to keep track of $i to insert a new element:

while ($stmt1->fetch()) {
    $data = []; //Initialize empty array. This is PHP 5.4+ syntax.
    while ($stmt2->fetch()) {
        $data[] = $someValue; //$array[] means "Push new element to this array"
    }
}

Method B is not neccessary. If you unset a non-existing variable nothing will happen, you won't get an undefined variable error.

You can see this behaviour here (it has error_reporting(E_ALL)).

Just in case you see it is some other code, I've already seen something like the following code (It's not the real code, only to give an idea of the use case).

The isset what used like "isset and with validated value". I'm not saying it's good practice (of course it's not, and even worse in this simplified example), it's just to show that, with overloaded magic methods, it may have some sense.

class unsetExample {

  private $data = 'some_value';

  public function __isset($name) {
    if ($this->${name} != 'my_set_value') {
      return false;
    } else {
      return true;
  }

  public function __unset($name) {
    unset($this->${name});
    echo 'Value unset';
  }

}

$u = new unsetExample;

if (isset($u->data)) {
  unset($u->data);
} else {
  echo 'In that case I don\'t want to unset, but I will do something else instead';
}

Edit : Changed the code, it's much more how it was is the real code now