0

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.

3
  • 10
    If this is exactly what you have in the files, there is no way you'd get true as the output. Commented May 27, 2014 at 13:41
  • Ok, the problem is a little more complex but if this is how it is suppose to work I know I'm in the right direction. I will keep looking into it, thanks. Commented May 27, 2014 at 13:54
  • Then, you should either delete your question, or edit it with more details. Commented May 27, 2014 at 14:17

1 Answer 1

1

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!
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this is exactly what I was looking for. I have now been able to figure out my issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.