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?

northamerican
  • 1,512
  • 1
  • 16
  • 27

4 Answers4

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.

Scopey
  • 6,120
  • 1
  • 20
  • 33
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 $$

Community
  • 1
  • 1
alamincse07
  • 11,674
  • 7
  • 29
  • 48
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

Community
  • 1
  • 1
xYuri
  • 378
  • 2
  • 16
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.

alamincse07
  • 11,674
  • 7
  • 29
  • 48
Steven
  • 1
  • 1