note 96407 modified in function.eval by danbrown

From: Date: Thu, 25 Feb 2010 18:39:12 +0000
Subject: note 96407 modified in function.eval by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-166357@lists.php.net to get a copy of this message
A simple use of eval: Sometimes you want to know both the value of a variable being passed to a function and its name. Passing by reference can get you there, but only through a lot of convolutions (as far as I can tell!) But by using the stem of a variable's name, there are two methods to achieve this. Say that <?php $emailName="me@example.com"; ?> You can pass this information thusly: First, if you have the stem, "emailName', in a string var <?php $theVarStem="emailName"; ?> you can recover the value of the original variable like this: <?php $theVarValue=eval("return \$$theVarStem;"); ?> Using 'return' inside the eval is the trick that makes it work - something inherent in the documentation but not at all obvious to me. Unless $emailName has global scope, this method won't work inside a function. For that purpose, you can do the following: <?php myFunction(compact("emailName")) function myFunction($theInfo) { $theVarStem=key($theInfo); $theVarValue=current($theInfo); //... } ?> I apologize if all this seems too obvious: it took me a lotta sloggin' to figure it out. --was-- A simple use of eval: Sometimes you want to know both the value of a variable being passed to a function and its name. Passing by reference can get you there, but only through a lot of convolutions (as far as I can tell!) But by using the stem of a variable's name, there are two methods to achieve this. Say that <? $emailName="me@q.com"; ?> You can pass this information thusly: First, if you have the stem, "emailName', in a string var <? $theVarStem="emailName"; ?> you can recover the value of the original variable like this: <? $theVarValue=eval("return \$$theVarStem;"); ?> Using 'return' inside the eval is the trick that makes it work - something inherent in the documentation but not at all obvious to me. Unless $emailName has global scope, this method won't work inside a function. For that purpose, you can do the following: <? myFunction(compact("emailName")) function myFunction($theInfo) { $theVarStem=key($theInfo); $theVarValue=current($theInfo); ... } ?> I apologize if all this seems too obvious: it took me a lotta sloggin' to figure it out. http://php.net/manual/en/function.eval.php

« previous php.notes (#166357) next »