NYCPHP Meetup

NYPHP.org

[nycphp-talk] Funny PHP Gotcha

Paul A Houle paul at devonianfarm.com
Thu Sep 10 15:19:28 EDT 2009


I ran into a gotcha today coding a PHP script...  The funny thing about 
it is that I've been writing PHP for years and haven't run into this one 
before..  The pattern is

function process_info() {
   foreach ($this->get_items() as $item) {
       // $data=array()             <--- this should have been here,  
but wasn't
       $data["X"]=$item->Y;
       if ($item->bar) {
          $data["foo"]=$item->bar;
       }
       $this->do_something_with_transformed_data_array($data);
   }
}

I was mystified by the behavior of the script -- eventually it dawned on 
me that I wasn't initializing the $data array with each loop...  I 
wanted $data["foo"] to be undefined if $item->bar evaluates false,  
however,  the value of "foo" was persisting between iterations,  causing 
do_something_with_transformed_data_array to behave horribly wrong...

    In some languages (C#,  for instance),  variables declared at a 
point in a loop come into existence at that point in the loop,  and 
don't have any life from one iteration to the next -- that kind of 
scoping certainly makes this kind of error less likely (unless $data was 
defined in front of the loop.)

    What I find interesting is that I don't remember ever making this 
sort of mistake in the past...



More information about the talk mailing list