可变范围方法{foreach{if(){variable}else{}}}

variable scope method{foreach{if(){variable}else{}}}

为什么这行得通?我以为变量只会在作用域内可见...或者是作用域方法?

1) 理想情况下:$variable-name 将在第一步用 foreach 定义...但是如何?
2) 为什么在整个 foreach 块中都可以访问 if 子句中定义的 $variable?
3) 在 PHPStorm 中出现编译错误,但代码有效...

数组对象__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++;
}

"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

因此,一旦定义了变量(在 foreach 循环中),它将在后续迭代中可见。

您可以在 PHPStorm 中禁用有关未定义变量的警告。有关详细信息,请参阅 this answer


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