I need to access $layers from inside the function isOk($layer), but everything i tried the outside function variable $layers is ok, but inside the function, even with global is return null.
Here is the code:
$layers = array();
foreach($pcb['PcbFile'] as $file){
if(!empty($file['layer'])){
$layers[$file['layer']] = 'ok';
}
}
// Prints OK!
var_dump($layers);
function isOk($layer){
global $layers;
// Not OK! prints NULL
var_dump($layers);
if(array_key_exists($layer, $layers))
return ' ok';
return '';
}
// NOT OK
echo isOk('MD');
I always use Object orientation, but this was something so simple that i made with a simple function… Why $layers is not being ‘received’ correcly inside the function?
Watch this…
HalfAssedFramework.php
example.php
Run
example.phpdirectly, and it should work. RunHalfAssedFramework.php, and it won’t.The problem is scope. When
example.phpis included inside therunfunction, all the code inside it inherits the function’s scope. In that scope,$layersisn’t global by default.To fix this, you have a couple of options:
example.phpwill never run directly, you can sayglobal $layers;at the beginning of the file. I’m not sure whether this will work if the script is run directly, though.$layerswith$GLOBALS['layers']everywhere.$layersas an argument toisOk.