In PHP, how does include() exactly work?

后端 未结 5 1926
别那么骄傲
别那么骄傲 2020-12-18 01:18

How does include(\'./code.php\'); work? I understand it is the equivalent of having the code \"pasted\" directly where the include occurs, but, for example:

5条回答
  •  悲哀的现实
    2020-12-18 01:41

    It depends on how you include the code.php file. If you include the code.php file into page1.php and then page2.php then you will have access to it's vars and it would effecitvely just "copy and paste" (beaware that is just used to make it easier to understand since the actual dynamics of that are explained above) the file in however if you link like:

    [code.php]
    include('page1.php');
    include('page2.php');
    

    Then code.php will have access to all of the variables within page1.php but:

    • page1.php will not have access to vars in code.php
    • page2.php will not have access to vars in code.php

    So in order to inherit the funcitonality of code.php inot both page1.php and page2.php be sure to do something like:

    [page1.php]
    include('code.php');
    
    [page2.php]
    include('code.php');
    

    Then it will work as you expect. So just something to remember there.

提交回复
热议问题