7
In C# there is the concept of local variables, see the example below:
if (true) {
int valor = 10;
}
else {
valor = 5;
}
Console.Write(valor);
The above code returns an error saying that the variable valor
does not exist in the current context:
error CS0103: The name `valor' does not exist in the current context Compilation failed: 1 error(s), 0 warnings
That is, the variable valor
exists only within the if
, and cannot access it outside the if
.
However, in PHP it doesn’t work the same as C#, see this example:
<?php
if (true) {
$valor = 10;
}
else {
$valor = 5;
}
echo 'Valor: ' . $valor;
The above PHP script output will be:
Value: 10
However, it is possible to access the variable valor
, even though it has not been stated in the same context or scope, it seems to be in some kind of global scope, and this has raised the following doubts.
Doubts
- All variables declared in PHP are global?
- Is there any way to declare local variables in PHP?
- If all variables are global in scope, their lifespan is according to the script lifetime?
http://php.net/manual/en/language.variables.scope.php. In the PHP documentation it is well explained.
– relaxeaza
@Rafaelmafra would be interesting to have an answer here also after all I think that this is the purpose of Sopt, I read the documentation, but I did not understand many things I was even more confused because it treats as if everything were local.
– gato