Parveez Ahmed
Parveez Ahmed

Reputation: 1417

Unset a variable without checking whether it has been already used or declared

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++;
   }
}

Upvotes: 0

Views: 88

Answers (3)

Clément Malet
Clément Malet

Reputation: 5090

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

Upvotes: 0

Lkopo
Lkopo

Reputation: 4835

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)).

Upvotes: 2

Madara's Ghost
Madara's Ghost

Reputation: 174957

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"
    }
}

Upvotes: 3

Related Questions