Re: Strange behaviour of static declared content.

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 10/18/07, Joshua Bacher <bacher@xxxxxxxxxx> wrote:
>
> Hi all,
>
> i faced the following problem.
>
> i am using a API. This API has a class that looks like following:
> <snip>
> class foo{
>         public function bar(){
>                 static $foobar=false;
>                 if ($foobar === False){
>                         $foobar='FUBeyondAllR';
>                         echo "$foobar\n";
>                 }else{echo "already defined\n";}
>         }
> }
> </snip>
> if you call the method of this class twice it will first print
> FUBeyondAllR and at the second time it will echo 'already defined'.
> (examples at the next and the last snippet)
>
> thats fine but what if you have some processing in the first if case? it
> would make sense then to unset this variable, right? No way, you can't
> acces it:
>
> <snip>
> $f=new foo();
> $f->bar();
> $f->bar();
> foo::$foobar=false;
> $f->bar();
> </snip>
>
> will lead to the following (called by `php5 fubar.php`):
>
> <snip>
> FUBeyondAllR
> already defined
>
> Fatal error: Access to undeclared static property:  foo::$foobar in xxxxx
> on line 14
> </snip>
>
> I need to recall the expressions encapsulated in the if-statement, but
> this
> fu variable behaves like it is protected, right? Does that make sense? Is
> there
> any way to unset this variable?
>
> I can't touch the API.
>
> Thanks for your suggestions and your time.
>
> josh
>

i have never use static variables inside of functions and likely never will.
go for static class variables instead :)

<?php
class foo{
        public static $foobar = false;
        public function bar(){
                static $foobar=false;
                if (self::$foobar === False){
                        self::$foobar='FUBeyondAllR';
                        echo self::$foobar . "\n";
                }else{echo "already defined\n";}
        }
}

$f=new foo();
$f->bar();
$f->bar();
foo::$foobar=false;
$f->bar();
?>

nathan@devel ~/working/www/siuConference $ php testScript.php
FUBeyondAllR
already defined
FUBeyondAllR

-nathan

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux