PHP/Language Basics/Variable Scope
Содержание
- 1 Defining Variable Scope
- 2 local variables
- 3 More Working with Variable Scope
- 4 Scope of a Variable
- 5 Use variable defined outside function
- 6 Variable Scope
- 7 Variable Scope: A Variable Declared Within a Function Is Unavailable Outside the Function
- 8 Variable scope: function
- 9 Variable Scope in Functions
- 10 Variables Defined Outside Functions Are Inaccessible from Within a Function by Default
Defining Variable Scope
<source lang="html4strict">
<?php $a = 7; function test() {
$a = 20;
} test(); echo "\$a = $a\n"; ?>
</source>
local variables
<source lang="html4strict">
<?php $x = 4; function assignx () {
$x = 0; print "\ $x inside function is $x.
";
}
assignx();
print "\ $x outside of function is $x.
";
?>
</source>
More Working with Variable Scope
<source lang="html4strict">
<?php
function getglobal() { global $my_global; echo "The value of \$foobar is "$foobar"
"; } $my_global = 20; getglobal();
?>
</source>
Scope of a Variable
<source lang="html4strict">
<?php
$a = "asdf"; function music (){ $a = "Music is great"; } print $a;
?>
</source>
Use variable defined outside function
<source lang="html4strict">
<?php
$ilike = "Rock"; function music(){ echo "I love listening to $ilike music!", "\n"; } music();
?>
</source>
Variable Scope
<source lang="html4strict">
<?php
$num; function make_triple($arg) { global $num; $num = $arg + $arg +$arg; thrice(); } function thrice() { global $num; echo("The value is $num"); }
?> <html>
<head> <title>Variable Scope</title> </head> <body>
<?php make_triple(4); ?>
</body>
</html>
</source>
<source lang="html4strict">
<html> <head> <title>Local Variable Unavailable Outside a Function</title> </head> <body>
<?php
function test() { $testvariable = "this is a test variable"; } print "test variable: $testvariable
";
?>
</body> </html>
</source>
Variable scope: function
<source lang="html4strict">
<?php
increment (); increment (); increment (); function increment () { $a=0; echo $a; $a++; }
?>
</source>
Variable Scope in Functions
<source lang="html4strict">
function foo( ) {
$bar = "wombat"; } $bar = "baz"; foo( ); print $bar; </source>
Variables Defined Outside Functions Are Inaccessible from Within a Function by Default
<source lang="html4strict">
<html>
<head>
<title>Variables Defined Outside Functions Are Inaccessible from Within a Function by Default</title>
</head>
<body>
<?php
$life = 42;
function meaningOfLife(){
print "The meaning of life is $life
";
} meaningOfLife(); ?> </body> </html>
</source>