How to use include within a function?

前端 未结 3 1895
刺人心
刺人心 2020-11-29 09:56

I have a large function that I wish to load only when it is needed. So I assume using include is the way to go. But I need several support functions as well -only used in go

3条回答
  •  既然无缘
    2020-11-29 10:41

    The problem with using include() within a function is that:

    include 'file1.php';
    
    function include2() {
      include 'file2.php';
    }
    

    file1.php will have global scope. file2.php's scope is local to the function include2.

    Now all functions are global in scope but variables are not. I'm not surprised this messes with include_once. If you really want to go this way—and honestly I wouldn't—you may need to borrow an old C/C++ preprocessor trick:

    if (!defined(FILE1_PHP)) {
      define(FILE1_PHP, true);
    
      // code here
    }
    

    If you want to go the way of lazy loading (which by the way can have opcode cache issues) use autoloading instead.

提交回复
热议问题