note 96407 added to function.eval

From: Date: Thu, 25 Feb 2010 18:35:56 +0000
Subject: note 96407 added to function.eval
Groups: php.notes 
Request: Send a blank email to php-notes+get-166356@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 <? $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. ---- Server IP: 64.71.164.2 Probable Submitter: 75.168.118.179 ---- Manual Page -- http://www.php.net/manual/en/function.eval.php Edit -- https://master.php.net/note/edit/96407 Del: integrated -- https://master.php.net/note/delete/96407/integrated Del: useless -- https://master.php.net/note/delete/96407/useless Del: bad code -- https://master.php.net/note/delete/96407/bad+code Del: spam -- https://master.php.net/note/delete/96407/spam Del: non-english -- https://master.php.net/note/delete/96407/non-english Del: in docs -- https://master.php.net/note/delete/96407/in+docs Del: other reasons-- https://master.php.net/note/delete/96407 Reject -- https://master.php.net/note/reject/96407 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#166356) next »