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
- How to blend adsense inside your post?
- Formatting my post
- PHPWind-- A PHP forum script applcaition in China
- Google Adsense forum and pin number
- Promote your Forum/Blog/Website via major search Engines
- Datatable export excel wraptext and newline
- Test MySQL connection in php using xampp
- PHP, load EXCEL/CSV file to mysql
- Notepad++ - Add C++ compiler
- Solve SIR model -C++/MatLab/Python
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