note 79398 added to language.references

From: Date: Sun, 25 Nov 2007 08:47:10 +0000
Subject: note 79398 added to language.references
Groups: php.notes 
Request: Send a blank email to php-notes+get-132553@lists.php.net to get a copy of this message
I will describe how references interact with global variables. Consider the following example. You create a DOM tree and then you use two functions. The first chooses an arbitrary tree element, while the second uses that element. Let us use a global variable as the means of communication between the two functions: // global variable var $dom_el; test1(); // call first function test2(); // call second function function test1() { global $dom_el, $Doc; $dom_el = &$Doc->childNodes->item(0); } function test2() { global $dom_el; // $dom_el does not contain the reference! You cannot use it here. // I am using PHP 4.4.6 } If we assign a reference to the desired tree node in the first function then surprisingly the reference will disappear after the first function returns. That is, that reference is not saved in the global variable. Most likely, it is a feature of PHP 4 language. Specifically, I am using PHP 4.4.6. Thus, using a global variable to pass a reference from one function to another does not work. However, if we save the reference as a field of an object, then the reference is preserved. Therefore, we need to wrap the global variable in a class: class Pointer { var $i; function Pointer() { $this->i=null; } function set(&$_i) { $this->i = &$_i; } function &get() { return $this->i; } } ?> Now the code looks like this: $dom_el=new Pointer(); function test1() { global $dom_el, $Doc; $tmp = &$Doc->childNodes->item(0); $dom_cur->set($tmp); } function test2() { global $dom_el; $tmp = &$dom_cur->get(); //$tmp has the desired reference } ---- Server IP: 195.54.192.44 Probable Submitter: 89.109.2.32 ---- Manual Page -- http://www.php.net/manual/en/language.references.php Edit -- https://master.php.net/note/edit/79398 Del: integrated -- https://master.php.net/note/delete/79398/integrated Del: useless -- https://master.php.net/note/delete/79398/useless Del: bad code -- https://master.php.net/note/delete/79398/bad+code Del: spam -- https://master.php.net/note/delete/79398/spam Del: non-english -- https://master.php.net/note/delete/79398/non-english Del: in docs -- https://master.php.net/note/delete/79398/in+docs Del: other reasons-- https://master.php.net/note/delete/79398 Reject -- https://master.php.net/note/reject/79398 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#132553) next »