note 45969 deleted from function.include by aidan

From: Date: Sat, 15 Apr 2006 16:36:47 +0000
Subject: note 45969 deleted from function.include by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-108170@lists.php.net to get a copy of this message
Note Submitter: william~AT~phodex.dot.us ---- Need a way to simpify the passing of may variables to include files? Working on a project where you don't have access to every script involved? Is an eval or some other routine killing your access to $GLOBALS? Let us call this aproach Scope Linking. ----------------------------- We can "hijack" the $_SESSION superglobal (or any other) and use it for our own purposes (assuming it's not in use already). HERE'S HOW: ----------------------------- Main file (sample1.php): <?php include ('sample2.php'); $_SESSION['var3'] = array(); $var2 =& $_SESSION['var2']; $var3 =& $_SESSION['var3']; $var1 = "Origional var1"; $var2 = "Origional var2"; $var3 = array('house'=>'blue','car'=>'tired','jet'=>'scripted'); $results = &Funky(); echo "------------------------<br>\n"; echo "Sample1 Script Output<br>\n"; echo "Var1: $var1<br>\n"; echo "Var2: $var2<br>\n"; echo "Var3: ${var3['house']} ${var3['car']} ${var3['jet']}<br>\n"; echo "------------------------<br>\n"; ?> ----------------------------- ----------------------------- Included file (sample2.php): <?php function &Funky() { foreach ($_SESSION as $name=>$val ) { $$name =& $_SESSION["$name"]; } echo "------------------------<br>\n"; echo "Sample2 Script Output<br>\n"; echo "Var1: $var1<br>\n"; echo "Var2: $var2<br>\n"; echo "Var3: ${var3['house']} ${var3['car']} ${var3['jet']}<br>\n"; $var1 = 'Second var1'; $var2 = 'wow, both ways! var2 rulez!'; } ?> ----------------------------- OUTPUT: ------------------------ Sample2 Script Output Var1: Var2: Origional var2 ------------------------ Sample1 Script Output Var1: Origional var1 Var2: wow, both ways! var2 rulez! ------------------------ YES this means predeclairing your variables by referencing them to $_SESSION elements unless you prefer to use the longer form: <?php $_SESSION['var2'] = "here's var2"; ?> if you want all $GLOBALS has to offer you can be way less specific (grab it all, slower & only a copy): <?php foreach ($GLOBALS as $name=>$val ) { $_SESSION["$name"] = $val; } ?> To see what you have access to, paste this in at the point you're interested in: ----------------------------- <?php if(isset($_SESSION)) { foreach ($_SESSION as $key=>$val) { echo "$key -- $val <br>\n"; } } ?> ----------------------------- P. S. Because it's a superglobal you can get away without using compact, but compact() & extract() are another options to crack this nut.

« previous php.notes (#108170) next »