Sunday, March 25, 2007

References with global and static variables

The Zend Engine 1, driving PHP 4, implements the static and global modifier for variables in terms of references. For example, a true global variable imported inside a function scope with the global statement actually creates a reference to the global variable. This can lead to unexpected behaviour which the following example address.


<?php
function global_ref()
{
//在function中用global,static引入的变量其实是对此变量建立了一个引用reference,
//在function执行完之后会对应变量的值不会丢失。
global $obj;
var_dump($obj);
echo "<br/>";
$obj = &new stdclass;
}
global_ref();
global_ref();
?>

<br/>

<?php
function global_noref()
{
global $obj;
var_dump($obj);
echo "<br/>";
if(!isset($obj))
{
$obj = new stdclass;
}
else
{
echo "has set variable: \$obj. <br/>";
}
}
global_noref();
global_noref();
?>
A similar behaviour applies to the static statement. References are not stored statically:

<?php
function static_ref()
{
static $sta;
var_dump($sta);
if(!isset($sta))
{
$sta = &new stdclass;
}
$sta->num++;
}
static_ref();
static_ref();
static_ref();
?>

<?php
function static_noref()
{
static $sta;
var_dump($sta);
echo "<br>";
if(!isset($sta))
{
$sta = new stdclass;
}
$sta->num++;
}
static_noref();
static_noref();
static_noref();
?>

Using the global keyword inside a function to define a variable is essentially the same as passing the variable by reference as a parameter:

somefunction(){
global $var;
}

is the same as:

somefunction(& $a) {

}

The advantage to using the keyword is if you have a long list of variables needed by the function - you dont have to pass them every time you call the function.

No comments :