简体   繁体   中英

PHP how does include work when using variables?

I'm fairly new to PHP and am having trouble with variables. When I put everything in one PHP file, it works but my question is should this work? I am under the impression that when you include a file then the variables are also included. Assuming that is true, when connecting to a DB, is it good practice to connect in a separate PHP file then include that into pages where you need to use the DB?

page1.php

<?php
     $test = "true";
?>

page2.php

<?php
     $test = "false";
?>

home.php

<?php
     include 'page1.php';
     include 'page2.php';
     echo $test;
?>

Expected output false but I am getting true.

When you include a file, PHP compiler extends the code with code in included file. Basically the code:

 include 'page1.php';
 include 'page2.php';
 echo $test;

changes to:

 $test = "true";
 $test = "false";
 echo $test;

And you overwriting the $test variable.

including files is one of the methods to split and order logic in your project.

In some matters it provides performance benefits, when you include files only when you need them, and saves you from code duplication.

As for databases, it doesn't matter when or how you connect to it, often database connection related logic is held by separate file, just because it's easier to edit and mantain, similar to config files.

Also consider this part of code:

$PRODUCTION = 0; // defines if we are at home computer or at work

if( $PRODUCTION == 0 )
    include ("connect_home.php");
elseif( $PRODUCTION == 1 )
    include ("connect_work.php");
else
    die("Oops, something gone wrong."); //don't connect if we are in trouble!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM