To include raw JavaScript files into my pages, i've ended up using:
function include_js($jsfile, $basepath = JSPATH){
echo '<script type="text/javascript">';
include($basepath . $jsfile);
echo '</script>';
}
Works fine, and the PHP code inside these JS files is still executing fine, no problem here. But here is some pseudo code of what i used before:
<script>
var hello = '<?php echo $id; ?>';
</script>
So, here's the problem:
include_js()
function.Thus, i don't have access to any of my page's variables anymore. I could fix it with a global $id;
, but that was pseudo-code.
Actually, i have NO idea what variables i'll need to have access to.
Any idea how to solve that problem? If you have a better solution than what i'm actually doing inside include_js()
to achieve the same goal without the problem i'm talking about, that would be as much appreciated!
You could import all global variables (but Superglobals) into the local scope of the function where you do the include. I don't think it's really a good solution (as it's a hammer) but as you write in your question you don't know which variables are used, so you could localize them like:
$varname = $GLOBALS['varname'];
As an alternative you could inspect the JS file and/or provide the list of variables for a file and add it to the include function as an array. See another answer for some code example.
You could also first pre-include (and throw away) the js file, gather the warnings about undefined variables, import them and then include for real. Some more include/discard/return/variable related chunks of code.
You can use global variables, but a more robust way is to write your own "constant databases". Something like:
class ConstantDB{
public static function set($key, $value){
}
public static function get($key){
}
}
It's just very convenient in many cases. For your particular situation, then you can use
ConstantDB::set("my_id", $id);
and inside the include_js, you can use
ConstantDB::get("my_id");