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++;
}
1
  • 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 for that. Commented Apr 17, 2017 at 18:22

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.