Welcome Guest, Not a member yet? Register   Sign In
Convert string to variable?
#1

[eluser]Sven Delle[/eluser]
I'm trying to setup a routine for environment checking. In a config file I have something like:

Code:
$config['requirements'] = array(
   'PHP_VERSION_ID' => '50306',
    'mysqli_get_client_version()' => '50509'
);

I then load the config and send it to the view, and would like to use PHP variable variables like:

Code:
foreach($requirements)
{
    if($$req_key < $req_value)
    // which SHOULD in the first case convert to: if(PHP_VERSION_ID < '50306')
    {
        // Code here ...
    }
    else
    {
        // Code here ...
    }
}

But I get:
Message: Undefined variable: PHP_VERSION_ID

PHP_VERSION_ID is a valid variable if I echo it directly.

What do I have to do to convert the string to a variable and have it execute properly?
#2

[eluser]WanWizard[/eluser]
Use
Code:
if(${$req_key} < $req_value)
#3

[eluser]Aken[/eluser]
You'll get the same error. The problem is you're assuming that the variable variable is acting as a reference to the original value inside your $config array, when it is not. You're trying to retrieve the value of a variable that has not been defined or assigned a value yet.

I can't offer a code solution without knowing exactly what you're doing, since it looks like you've only provided a rough example of the steps you're taking (I have no idea where you're getting $req_key & $req_value, and to what you're trying to compare them to). But you'll need to assign the variable variable a value before comparing it to something.
#4

[eluser]Sven Delle[/eluser]
Thanks, but already tried that (should have put that in the post as well).

But unfortunately the same result.
#5

[eluser]Aken[/eluser]
I'm sure you did... Post your actual code, that'll help much more.
#6

[eluser]Sven Delle[/eluser]
Well, as it says in the php manual:

Quote:Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.

So, I guess this is a no go as I guess PHP_VERSION_ID is considered as such.

And by the way, that IS the actual code. I'm just testing the 'concept' if you like. And the variable is defined (in the $config array which is the sent to the view).

But I was obviously waaaaay to smart : ).
#7

[eluser]GrahamDj28[/eluser]
Try setting your variable variable in the controller and then send it to the view.




Theme © iAndrew 2016 - Forum software by © MyBB