function - php global variable not showing correct answer -
its simple code don't understand whats point :(
function aaa($b){ $a = 30; global $a,$c; return $c=($b+$a);} echo aaa(40); //output 40 why output 40 ? when call $a outside of function gives me desired answer point ?
$a = 30; function aaa($b){ global $a,$c; return $c=($b+$a); } echo aaa(40); //output 70 function aaa($b){ global $a,$c; $a = 30; return $c=($b+$a); } echo aaa(40); //output 70
see global keyword stands here:
function aaa($b) { $a = 30; # local variable, overwritten in next line global $a, $c; # importing $a global scope - null return $c = ($b + $a); # $c = (40 + null) } the manual @ http://php.net/global reminds global variable influences function if used inside there. not first call subsequent calls.
this makes function non-deterministic, less useful code , might - did - irritated it.
an easy way out is: instead of putting parametric values of function global variables, turn them parameters:
function aaa($a, $b, &$c) { return $c = ($b + $a); } echo aaa(30, 40, $c); //output 70 the code not easier read deterministic. behave same when called. means less guessing.
this example still has problem of returning value parameter (by reference), might see not necessary longer:
function aaa($a, $b) { return ($b + $a); } echo $c = aaa(30, 40); //output 70 lessons take away:
- do not use global variables inside functions - stand in way.
- reduce number of parameters function has (that all incomming values, global counts well).
Comments
Post a Comment