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!

2 Answers 2

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.

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

1 Comment

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!
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");

1 Comment

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 =)

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.