Witold Kowelski
Witold Kowelski

Reputation: 922

Convert String to Variable

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).

Upvotes: 1

Views: 2287

Answers (1)

Daryl Gill
Daryl Gill

Reputation: 5524

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!"

Upvotes: 7

Related Questions