Online computer courses, code, programming tutorial and sidebar information for monitoring Canadian S&P/TSX index. Build friendship and networking. Welcome to visit my blogs often!!! I also have two other sites: YouTube Channel and Google site.
Adsense
Popular Posts
- PHPWind-- A PHP forum script applcaition in China
- How to blend adsense inside your post?
- Formatting my post
- Notepad++ - Add C++ compiler
- Install PHPMailer 5.2.4 and use smtp gmail
- Set up a child account and set screen time limit in Windows 8
- Wayback Machine - see archived versions of web pages across time
- phpexcel toggle expand and hide column in EXCEL and summary
- Install PHP ibm_db2 extension in Linux (redHat)
- PHP: add a download as pdf file button in report page
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);
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment