1

Okay, so I want to know if there are any (other, and preferably easy) ways to convert a string to a variable.

My code, which works, is as follows:

echo eval('return $'. $date . ';');

$date contains a string. Now, the code works, and I'm fine with leaving it as it is if nothing else, since $date is called from a pre-programmed class declaration:

Time::Format($id = 'id', $name = 'name', $date = 'date->format(Y)');

The reason I ask is due to the PHP official disclaimer/warning on its use of: The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

As such, I think I am safe in using it, as there is no user-inputted data being eval'd by PHP, it's a string I set as the coder, but I would like a second opinion its use, as well as any input on another simple method to do this (since, if I can avoid it, I'd rather not use a complicated and possibly long block of code to accomplish something that can be done simply (provided it is safe to do quick and dirty).

1 Answer 1

7

PHP's variable variables will help you out here. You can use them by prefixing the variable with another dollar sign:

$foo = "Hello, world!";
$bar = "foo";
echo $$bar; // outputs "Hello, world!"
Sign up to request clarification or add additional context in comments.

3 Comments

Well, that does work to output (in my example) "date->format(Y)" it does not work to convert the string to a variable and do what eval does to it (and allow for it's execution as a variable). Since using eval, when I echo the eval of $date as a variable, it echo's a user-inputted year (as it was hard-coded to do). PHP's variable variables, albeit interesting doesn't exactly answer my question.
Instead of converting the string to a variable, why don't you store the string in a variable then call it as required?
As far as I can see, the only way to get it to work is to convert the string to a variable since the string has to be a variable to work. date->format(Y) won't do a thing, but $date->format(Y) works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.