dongzhi5386 2014-01-26 18:19
浏览 40

php:全局变量混乱[重复]

Things got a little bit messy when trying to use a library I made. This is what my project looks like without the unnecessary content.

lib_vars.php

<?php $lib_var = 10;?>

lib.php

<?php
    require_once('lib_vars.php');
    function lib_func(){
        global $lib_var;
        echo $lib_var;
    }
?>

action.php

<?php
    require_once('lib/lib.php');
    function action(){
        lib_func();
    }
?>

index.php

<?php
    require_once('action.php');
    function main(){
        if(true)
            action();
    }
    main();
?>

For some reason I have to place require_once('action.php') on top of index.php. If I place it in the if-statement, It can't find $lib_var any more. If I have 10 different actions in index.php, than I would be forced to include 9 unnecessary files. Does someone know an alternative?

Thanks.

</div>
  • 写回答

1条回答 默认 最新

  • douyun1950 2014-05-23 10:20
    关注

    You don't have to place require_once('action.php') on top of index.php but if you include anything within limited scope then you have to manually export all variables included by it as globals. Similarily, if you want to use global variables in included file, you have to "import" them. See example here of using extract to do such things: https://stackoverflow.com/a/10144260/925196

    评论

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本