I have thought about this for a while. $s1 is set in a foreach loop and can access after the loop, meanwhile $s2 is set in a function say and can't access after because it is local variable. My question is: Are variables in iterators consider global?
<?php
$systems = array('windows', 'mac', 'linux');
foreach ($systems as $s) {
$s1 = $systems[0];
}
echo $s1 . '<br />'; // Echo out "windows"
function say(){
$s2 = 'skynet';
echo $s2;
}
say(); // Echo out "skynet"
echo $s2; // Undefined variable
?>
When you declare an iterator, such as foreach()
, then the code will be executed at runtime.
When you declare a function()
, the code is not executed at runtime. It will only be run through when you call the function.
This is why $1
is defined, but $2
is not.
Variables in functions (or class methods) are always local.
In php there are two types of variables:
No, in your context $s1
is not global, it simply is at the same level as your print line. Otherwise your $s2
var is private and exists only inside the say()
function.
If you declare global $s1;
, then $s1 is global. Otherwise, it is not global. If it is not global, then it is accessible only from the same scope where it is defined. In simple terms, if you write $x=1
, then you can get the value of $x
from anywhere except inside functions, until the function you defined it in ends.
All your answers are here: http://php.net/manual/en/language.variables.scope.php