dongshun1884 2012-01-29 18:24
浏览 32
已采纳

PHP:模拟函数内未知变量的全局行为

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条回答 默认 最新

  • dongsu0308 2012-01-29 18:57
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了