AlexMorley-Finch
AlexMorley-Finch

Reputation: 6955

do included files in php use information from the files that included them?

Say I have a the following files

Example 1

functions.php

<?php
     session_start();
     function getSessionData(){
         ...
         // returns array
     }
?>

index.php

<?php
    session_start();
    include("functions.php");
    $sessionData = getSessionData();
?>
<html>
    <head>
        <title>test</title>
    </head>
    <body>
        <?php print_r($sessionData); ?>
    </body>
</html>

Now the index.php includes functions.php. Because I have session_start() in index.php, does this mean it's automatically added in the functions.php (seeing as functions is included in index?)

Im not sure if im making this clear or not.

Example 2

config.php

<?php
    $url = "www.example.com";
?>

functions.php

<?php
     include("config.php");
     function getSomething(){
         ...
         return $url
     }
?>

index.php

<?php
    include("config.php");
    include("functions.php");
    $some_var = getSomething();
?>
<html>
    <head>
        <title>test</title>
    </head>
    <body>
        <?=$some_var;?>
    </body>
</html>

Now both functions.php AND index.php include config.php...

But because config is already included in index.php...

does this mean it has to be included functions aswel?

I think I've just confused myself tbh:)

Upvotes: 1

Views: 74

Answers (1)

Ross
Ross

Reputation: 46987

Yes. You can think of includes as simply pasting the code in the file where the include statement is.

In example 2, you don't need to include config again in index, as it has already been included in functions (or vice versa) - what you're actually doing there is running the code in config.php twice (which can be prevented by using include_once for example).

The same goes for session_start() in example 1. When index is loaded the following happens:

  1. session_start
  2. include functions.php
    1. session_start (not needed now)
    2. function getSessionData() {..}
  3. (back to index) - call getSessionData()

Also, in your second example, you won't be able to access $url in that function without calling global $url before it (inside the function).

Upvotes: 6

Related Questions