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

    评论

报告相同问题?