note 111081 deleted from function.preg-replace-callback by googleguy
| From: | googleguy@php.net | Date: | Sat, 12 Jan 2013 12:09:47 +0000 |
| Subject: | note 111081 deleted from function.preg-replace-callback by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-192992@lists.php.net to get a copy of this message | ||
Note Submitter: admin at french-web-proxy dot fr
----
I Would add a note about varable scope in a function created threw a runetime created function...
<?php
//for exemple
$replace_text='bar';
$foo='foo';
$replace_text=preg_replace_callback('#bar#',
create_function('$result','
global $foo;
$foo=$result; //set variable to bar
//$foo is destroyed here
')
,$replace_text);
echo $foo; //print 'foo' and not 'bar'
?>
the solution is to use superglobals variables...for example $_SERVER
<?php
$replace_text='bar';
$_SERVER['foo']='foo';
$replace_text=preg_replace_callback('#bar#',
create_function('$result','
//global $_SERVER["foo"]; <--don t need this
$_SERVER["foo"]=$result; //set variable to bar
')
,$replace_text);
echo $_SERVER['foo']; //print 'foo' and not 'bar'
?>
here it is ;)