+ 1
can you explain me the usefulness of global and local scope more detail ?
7 Réponses
+ 6
for example when you are using variables in a function you are declaring variables in a local scope meaning they wont be effected from outside the function , and the global scope is everything outside the function. the same goes for loops unless you declare those variables before the loop.
<?php
$varone = 1 ;
// global scope
function myfunction(){
$varone = 2 ;
// local scope
}
echo $varone;
//result 1
?>
+ 2
variables in local scope will be used only in that function and won't be affected by outside of an function, and that variable is only accessible to that function. it's helping to avoid conflict with global....
but u can use global in function:
<?php
$name="marko"; //global variable
function getName() { //creating function
global $name; //define to use global variable $name
echo $name; // function will outprint global variable $name
}
getName(); //calling function to do it's work
?>
0
when you are declaring in global scope the variable can't be accessed inside the function, it may avoid conflicts when you are using same name on both ends...
0
Hey babe,
Local scope is restrictive to particular methods or functions. Meaning variables created within the curly, are only accessible to that particular block.
e.g.
$name = "nath";
function hi(){
$s = 4;
echo $d = GLOBAL $name , "local";
#note we can access global vars in local scope.
}
#s is dead here.
echo $name;
Hope this helps.
0
Simon, my point being globals can be accessed in local scope.
Ref: http://php.net/manual/en/language.variables.scope.php
0
For example you are useful as a person for your family, is a local scope and you are useful as a programmer for the world, is a global scope.
0
to understand the meaning of scopes u can imagine scopes as rooms or apartments in building. for example u whant to have several variables with same names but multiply defenitions. for example u have john from 14th apartment and he is doctor but theres anothere john who is fireman and he is liveing in 23rd apartment. u cant call to john which is fireman when you in 14th app-nt.