Skip to content

Instantly share code, notes, and snippets.

@mkantor
Last active December 17, 2015 00:09
Show Gist options
  • Save mkantor/5518331 to your computer and use it in GitHub Desktop.
Save mkantor/5518331 to your computer and use it in GitHub Desktop.
Demonstrate PHP's function scoping.
<pre>
<?php
$x = 'value set in global scope';
function namedFunction() {
echo 'in '.__FUNCTION__.', before setting $x: $x === '.var_export($x, true)."\n";
$x = 'value set in '.__FUNCTION__;
echo 'in '.__FUNCTION__.', after setting $x: $x === '.var_export($x, true)."\n";
}
$anonymousFunction = function() {
echo 'in '.__FUNCTION__.', before setting $x: $x === '.var_export($x, true)."\n";
$x = 'value set in '.__FUNCTION__;
echo 'in '.__FUNCTION__.', after setting $x: $x === '.var_export($x, true)."\n";
};
echo 'in global scope, before calling functions: $x === '.var_export($x, true)."\n";
echo 'calling namedFunction()...'."\n";
namedFunction();
echo 'calling $anonymousFunction()...'."\n";
$anonymousFunction();
echo 'in global scope, after calling functions: $x === '.var_export($x, true)."\n";
?>
</pre>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment