js and php scopes difference
- js in scope:
- Global scope: anywhere (outside and function within a function) can be used
- The local scope: function can only be used internally
- PHP also has two scopes: global scope and local scope
- Global scope: it can only be used outside the function
- The local scope: it can only be used within the function
such as:
var a = 'zy'
function test () {
console.log(a)
}
test()
// a 变量可以被访问到
Internal not external
<?php
$a = 'zy'
function test () {
var_dump($a)
}
test()
?>
// 报错:( ! ) Parse error: syntax error, unexpected 'function' (T_FUNCTION) in
External can not access the internal
<?php
function test () {
$a = 'zy'
}
var_dump($a)
?>
// 报错:( ! ) Parse error: syntax error, unexpected '}' in
Use global keywords
<?php
function test ()
{
global $a;
}
$a = 'zy';
var_dump($a);
test();
// 好使
Use $ GLOBALS
<?php
function test ()
{
$GLOBALS['a'] = 'zy';
}
test();
var_dump($GLOBALS['a']);