Variables not working in Include file

Discussion in 'PHP' started by jdoerr, Apr 21, 2011.

  1. #1
    I've read on tutorial web sites that if you set a variable in a file and the include another file that references that variable, it'll work, but it isn't working for me. Here's an example of my code:

    http://www.mysite.com/folder/thisfile.php
    
    <?php
    $testvariable = "test";
    include("http://www.mysite.com/test.php");
    ?>
    
    PHP:
    http://www.mysite.com/test.php
    
    <?php
    echo "Output: ". $testvariable;
    ?>
    
    PHP:
    And the page only says "Output: "

    Could it be because it's including a file that's not in the same folder? I don't understand why it's not working. Any help would be appreciated!
     
    jdoerr, Apr 21, 2011 IP
  2. stephan2307

    stephan2307 Well-Known Member

    Messages:
    1,277
    Likes Received:
    33
    Best Answers:
    7
    Trophy Points:
    150
    #2
    You are doing it wrong. try this

    http://www.mysite.com/folder/thisfile.php
    <?php
    $testvariable = "test";
    ?>
    PHP:
    http://www.mysite.com/test.php
    <?php
    include("folder/thisfile.php");
    echo "Output: ". $testvariable;
    ?>
    PHP:
     
    stephan2307, Apr 21, 2011 IP
  3. jdoerr

    jdoerr Active Member

    Messages:
    121
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    55
    #3
    That won't allow me to do what I'm trying to do though. I want to have several folders with a file that all include the 'test.php' file, but with a different variable. If that's not possible, then I guess I'll have to go back to the drawing board and figure out a different way to accomplish what I'm trying to do.
     
    jdoerr, Apr 21, 2011 IP
  4. x319

    x319 Well-Known Member

    Messages:
    90
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    103
    #4
    You can rather define the variable instead.

    
    // folder/thisfile.php
    <?php
        define('TESTVARIABLE', 'test');
        include '../test.php';
    ?>
    
    // test.php
    <?php
        echo defined('TESTVARIABLE') ? TESTVARIABLE : 'TESTVARIABLE not found...';
    ?>
    
    PHP:
     
    x319, Apr 21, 2011 IP
  5. salmanshafiq

    salmanshafiq Well-Known Member

    Messages:
    260
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    128
    #5
    You should you Constant for this because Variable on have the value within the include File.
     
    salmanshafiq, Apr 21, 2011 IP