How to use include within a function?

前端 未结 3 1898
刺人心
刺人心 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条回答
  •  猫巷女王i
    2020-11-29 10:57

    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.

    Your base assumption is wrong. This kind of optimization is counter-productive; even if your function is hundreds of lines long there will be no noticeable benefit to hiding it from PHP's parser. The cost for PHP to parse a file is negligible; real noticeable speed gains come from finding better algorithms or from better ways to talk to your database.

    That said, you should be including the function definition in the included file. Rather than moving the body of the function into func_1.php, move the entire function into the file. You can then require_once the file containing the function inside each file where you need it, and be sure that it is included exactly once regardless of how many times you attempt to include it.

    An example:

    file1.php

    function test() {
    
    }
    

    index.php

    require_once('file1.php');
    
    include('table_of_contents.php');
    test();
    

提交回复
热议问题