1

Why does this work? I thought variables would only be visible within scope... Or is the scope method?

1) Ideally: $variable-name would be defined first step with foreach... but how?
2) why is $variable defined in the if clause accessible in the whole foreach block?
3) in PHPStorm I get an compile error, but the code works...

ArrayObject __construct:

// read JSON
foreach ($jsonIterator as $key => $val) {

    if ($jsonIterator->getDepth()===0){

        $variable = new Preguntas_Educacion_V1($key);
        $this->offsetSet($variable->getColumn(),$variable);
    } else if ($jsonIterator->getDepth()===1){

        //Reflection!!! call setter dynamically by Val

        $function="set".ucfirst($key);
        $variable->$function($val);
    } else if ($jsonIterator->getDepth()===2){
            //Respuestas array
    }

    $counter++;
}
Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
Canelo Digital
  • 340
  • 2
  • 10
  • 1
    If it's been set in a previous iteration, it's still defined in the next iteration (its defined until the end of the script unless `unset()` or set equal to null), even if a different condition is met. If you want to read about scopes, [this is a good thread](http://stackoverflow.com/q/16959576/4535200) for that. – Qirel Apr 17 '17 at 18:22

1 Answers1

1

"The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. ... However, within user-defined functions a local function scope is introduced."1

Thus once the variable is defined (in the foreach loop) it will be visible in subsequent iterations.

You can disable warnings about undefined variables in PHPStorm. For more information, see this answer.


1http://php.net/manual/en/language.variables.scope.php

Community
  • 1
  • 1
Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58