In the first case you actually pass the value to the PHP script, where <?php echo $test; ?>
is parsed by PHP parser and replaced by the value of $test
PHP variable.
In the second case you just include '<?php echo $test; ?>
' string into JS file and this is not parsed.
My suggestion is: pass this value the way you are passing now, but properly reference it from the external JS file. For example you can invoke some function defined in JS file, passing the parameter from PHP file.
There is also the ugly way of doing that, such as making your server treat JS files as PHP files, but I am not recommending it.
Some example:
If you include in your PHP file:
<script type="text/javascript" src="foo.js"></script>
<script type="text/javascript">myHappyFunction("<?php echo $test; ?>")</script>
and in your JS file (foo.js):
(function(){
var myHappyFunction = function(myParameter){
alert(myParameter);
};
window['myHappyFunction'] = myHappyFunction; // pass outside scope
})();
you should see $test
value being alerted when the script executes (assuming I did not make a mistake writing this ;)).