0

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:

  • Before, the PHP code used inside my JavaScript files was executed in the same context as the page's one.
  • Now, it's executed in the context of the 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!

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
aaaaaa
  • 2,588
  • 3
  • 26
  • 31

2 Answers2

1

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");
Matthieu Napoli
  • 48,448
  • 45
  • 173
  • 261
hiro
  • 261
  • 7
  • 19
  • That's a good answer, i already thought about doing that, but i'd rather use something that doesn't require me to re-write a whole bunch of code. I'll accept your answer later if nothing better comes up =) – aaaaaa Jan 29 '12 at 18:49
1

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.

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836
  • I'll give my function an array of variables to use. +1 for making me discover the `extract()` function through your first example, which is really awesome! – aaaaaa Jan 29 '12 at 20:30