Unset won't work?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • frizzle

    Unset won't work?

    Hi group,

    Why won't $new_var be unset in the following function?
    Am i missing out something?

    Greetings Frizzle.

    *************** *************** *******


    function DoThis( $state, $fst = 1, $scnd = 2)
    {
    if( $state === 0 )
    {
    global $new_var;
    unset($new_var) ;
    }
    else
    {
    global $new_var;
    return $new_var = $fst + $scnd;
    };
    };


    echo DoThis( 1, 4, 8);
    echo DoThis( 0 );
    echo 'new_var= '.$new_var;

  • Marcin Dobrucki

    #2
    Re: Unset won't work?

    frizzle wrote:[color=blue]
    > Hi group,
    >
    > Why won't $new_var be unset in the following function?
    > Am i missing out something?
    >
    > Greetings Frizzle.
    >
    > *************** *************** *******
    >
    >
    > function DoThis( $state, $fst = 1, $scnd = 2)
    > {
    > if( $state === 0 )
    > {
    > global $new_var;
    > unset($new_var) ;[/color]

    - global $new_var;
    - unset($new_var) ;
    + unset($GLOBAL['new_var'];

    See the docs for details (www.php.net/unset)
    [color=blue]
    > }
    > else
    > {
    > global $new_var;
    > return $new_var = $fst + $scnd;
    > };
    > };
    >
    >
    > echo DoThis( 1, 4, 8);
    > echo DoThis( 0 );
    > echo 'new_var= '.$new_var;[/color]

    Note: you don't need ; after the curly braces. And you should
    probably also initialize the $new_var before DoThis();

    Anyway, IMHO, unsetting global variables within functions is a sure
    way of shooting yourself in the foot. BTW, because you actually unset
    the variable the last line will throw a notice about undef variable.

    /m

    Comment

    Working...