Re: Variable within a Variable

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



At 06:54 PM 4/9/2006, bob pilly wrote:
Im trying to store a document template in mysql that has php var names within it and then find it in the datebase and print it out with the var names replaced with the var values.


At 04:05 PM 4/7/2006, Paul Novitski wrote:
At 02:41 PM 4/7/2006, David Clough wrote:
I have to parse the string 'Hello $foo' as it comes from the
database: I don't get to construct it.

I did hold out more hope for the eval function, but it seems to me that
this is for PHP code in a database, not to evaluate variables.


David, please try the eval() route: it will do what you want. You say, "this is for PHP code in a database, not to evaluate variables," but evaluating variables is absolutely part of PHP code processing! Eval() will operate on "$x = 4;" just as easily as on "Hello $foo."

You should not use eval() frivolously because it presents a potential vulnerability in your code. You may wish to ensure that the database text it operates on is first cleansed of any other PHP syntax -- similarly to the way we should all ensure that any incoming data is clean before we process it and incorporate it into our scripts.

Here's an example of variaible evaluation:
_______________________

$bar = "cat";
$foo = "Hello \$bar.";

echo $foo;
RESULT: Hello $bar.

By escaping the $, I have made it a literal character in the text, the same as if I'd read "Hello $bar" from a database.
_______________________

eval("echo \"$foo\";");
RESULT: Hello cat.

This is equivalent to scripting:
        echo "$foo";
I'm using eval() to execute the echo command and interpret the PHP variable $foo.
_______________________

eval("\$dog = \$bar;");
echo "dog = " . $dog;

RESULT: dog = cat

Here I'm using eval() to set one PHP variable equal to another.
_______________________

You can't simply write:
        eval("\$bar;");
or
        $x = eval($foo);

because everything inside the eval() parentheses needs to be a complete PHP statement. The eval() function itself doesn't return the value of an evaluated expression. To capture the value of an expression, you must evaluate a complete statement that sets a variable equal to the expression as above.
_______________________

Clear as mud?

Regards,
Paul

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux