PHP/Language Basics/GLOBALS — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Версия 13:37, 26 мая 2010
Содержание
Accessing Global Variables with the global Statement
<source lang="html4strict">
<html> <head><title>The global Statement</title></head> <body>
<?php
$life=42; function meaningOfLife() { global $life; print "The meaning of life is $life
"; } meaningOfLife();
?>
</body> </html>
</source>
Create global variables
<source lang="html4strict">
<?php $somevar = 15; function addit() {
GLOBAL $somevar; $somevar++; print "Somevar is $somevar";
} addit(); ?>
</source>
$GLOBALS with property
<source lang="html4strict">
<?php $a = 7; function test() {
$GLOBALS["a"] = 20;
} test(); echo "\$a = $a\n"; ?>
</source>
Global vs function level
<source lang="html4strict">
<?php $a = 7; function test() {
global $a; $a = 20;
} test(); echo "\$a = $a\n"; ?>
</source>
Looping Through the $GLOBALS Array
<source lang="html4strict">
<html> <head> <title>Looping through the $GLOBALS array</title> </head> <body> <?php foreach ( $GLOBALS as $key=>$value ){
print "\$GLOBALS[\"$key\"] == $value
";
} ?> </body> </html>
</source>
Modifying a Variable with $GLOBALS
<source lang="html4strict">
<? $dinner = "Curry"; function hungry_dinner() {
$GLOBALS["dinner"] .= " and Fried";
} print "Regular dinner is $dinner"; print "\n"; hungry_dinner(); print "Hungry dinner is $dinner"; ?>
</source>
Overriding Scope with the GLOBALS Array
<source lang="html4strict">
function foo( ) {
$GLOBALS["bar"] = "wombat"; } $bar = "baz"; foo( ); print $bar; </source>
Set new value into GLOBALS values
<source lang="html4strict">
<?php
$somevar = 15; function addit() { $GLOBALS["somevar"]++; } addit(); print "Somevar is ".$GLOBALS["somevar"];
?>
</source>