0

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.

JMRC
  • 1,473
  • 1
  • 17
  • 36

1 Answers1

1

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

Community
  • 1
  • 1
Grzegorz Adam Kowalski
  • 5,243
  • 3
  • 29
  • 40