Tuesday, November 12, 2013

PHP, global variable and local variable



In PHP programming, we should be careful of the scope of global variable and local variables.
Example 1: the $a variable inside test function is not related to the global varialbe $a outside test function, and default is 0
<?php
$a = 2; /* global scope */
function test()
{
    $a=$a+1;
    echo $a.'<br />'; /* reference to local scope variable */
}
test();
test();
echo $a;
?>

The result is
1
1
2

Example 2: now we declare $a as a global variable inside function test, it is  the same as the $a  variable defined  outside the test function
<?php
$a = 2; /* global scope */

function test()
{
   global $a;
    $a=$a+1;
    echo $a.'<br />'; /* reference to local scope variable */
}

test();
test();
echo $a;
?>

The result is
3
4
4
Example 3: global variable $db is often used in mysql_query($sql, $db) in PHP functions,
and  static variable $now is used to memorize its first  value, after first time call write_to_rplog function,  the variable $now is set. 
function write_to_rplog($operation_type, $table_name, $num_affected, $details) {
    global $db;
    static $now;
 
    if (!$now) {
        $now = date('Y-m-d H:i:s');
    }
    if ($num_affected > 0) {
        $details = addslashes(stripslashes($details));
        $sql    = "INSERT INTO  rp_admin_log VALUES ('$_SESSION[login]', '$now', '$operation_type', '$table_name', $num_affected, '$details')";
        $result = mysql_query($sql, $db);
    }
}

No comments:

Post a Comment