0

I'm trying to convert a PHP variable to a JS variable using a little helper function that uses variable variables. To simplify, here is what I'm trying to accomplish:

 $project_key = 'project 1';

 function to_js($variable) {
     echo $$variable;
 }

 to_js('$project_key');

this is supposed simply print

project 1

instead i get

Undefined variable: $project_key

which tells me the variable is being targeted but can't be accessed from the function. How can I access the global var $project_key from within the function if supplied only with the string $project_key?

4 Answers 4

4

Omit the leading $ from $project_key in the following line:

to_js('$project_key');

It should be:

to_js('project_key');

The $ in a variable is not part of the variables name, so you don't need to include it when referencing it in a variable variable.

Sign up to request clarification or add additional context in comments.

Comments

1

Remove first $ sign before $variable. If you use $$ the project 1 will be considered as a variable but that is not defined as a variable.

$project_key = 'project 1';

function to_js($variable) {
    echo $variable;
}

to_js($project_key);

Reference of $$

1 Comment

let's define it. global $$variable; no error, no output :)
0

Try echoing your variable with script tags around it.

echo "<script>var x =" . $variable . "</script>";

$variable - being the variable you have stored in php x - being the variable you want to be stored in Javascript.

Comments

0

Try removing the quotes in:

to_js('$project_key');


To be to_js($project_key); as if you use it as to_js('$project_key'); then you set the $variable in the function to the text: '$project_key'.

Wrong answer!

@mehedi-pstu2k9 answer's is correct

Reference of $$


See:
https://stackoverflow.com/a/4169891/4977144

Comments

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.