test()
{
global $myglobal;
$mylocal =& $myglobal;
echo "local: " . $mylocal . "n";
echo "gloal: " . $myglobal . "n";
}
test();
?>
Pascal example:
program dontcare;
var myglobal: integer;
procedure test;
var mylocal ABSOLUTE myglobal;
begin
write("local: ", mylocal);
write("global: ", myglobal);
end;
begin
myglobal := 5;
test;
end.
By the way, a "local" keyword in php for local variables,
could be welcome :-)
In reply to pike at kw dot nl, '&' is only apply to PHP 4.
PHP 5 changed the behavior and the object is defaultly passed by references and if you turn on E_STRICT, you will get a notice:
Strict Standards: Assigning the return value of new by reference is deprecated in xxxx
If you want to *copy* object in PHP 5, use object clone.
if your object seems to "forget" assignments you make after instantiation, realize that in
$foo = new Bar()
the variable on the left hand is a *copy* of the variable on the right hand. As a result, & references made during instantiation may point to the righthandside version of Bar() and not to $foo. you'd better use
$foo = & new Bar()
I found a very useful summary of how references work in PHP4 (and some of the common pitfalls) in this article: http://www.obdev.at/developers/articles/00002.html
It deals with some subtle situations and I recommend it to anyone having difficulty with their references.
I found a subtle feature of references that caused a bug in one of my PHP applications. In short, if an object passes one of its members to an external function that takes a reference as an argument, the external function can turn that member into a reference to an anonymous point in memory.
Why is this a problem? Later, when you copy the object with $a = $b, the copy and the original share memory.
Solution: If you want to have a function that uses references to modify a member of your object, your object should never pass the member to the function directly. It should first make a copy of the member. Then give that copy to the function. Then copy the new value of that copy in to your original object member.
Below is some code that can reporoduce the this feature and demonstrate the workaround.
function modify1 ( &$pointer_obj ){
$pointer_obj->property = 'Original Value';
}
function modify2 ( &$pointer_obj ){
$newObj->property = 'Original Value';
$pointer_obj = $newObj;
}
class a {
var $i; # an object with properties
function corrupt1(){
modify1 ($this->i);
}
function doNotCorrupt1(){
20/24 首页 上一页 18 19 20 21 22 23 下一页 尾页 |