PHP variable not working when referenced with '$'
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
?
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.
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 $$
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.
下一篇: 当用'$'引用PHP变量不工作