0

Let's say I hava a page index.php and in it I execute:

require_once("file1.php");
echo $myVar;

in file1.php I have:

require_once("file2.php");

and in file2.php I have

$myVar = "test";

After executing this script, index.php can't get to $myVar and outputs undefined variable. Any reason on that ?

6
  • 1
    Something else is affecting $myVar that you're not putting here. As it stands this problem can't be reproduced by your example. Commented Nov 17, 2014 at 18:23
  • there is no issue with this.. Commented Nov 17, 2014 at 18:23
  • Works for me. There must be some other code that is relevant. Commented Nov 17, 2014 at 18:23
  • 1
    Are you including file1.php or file2.php in some other location first? require_once will only include the file if it has not already been included. Commented Nov 17, 2014 at 18:25
  • first try it guys, and then say it's something wrong with my code. I've been doing PHP for 5 years but it's the first time when I try 2-level include var scope... Commented Nov 17, 2014 at 18:40

1 Answer 1

2

require/include act as if the contents of the file being included were literally cut/pasted into the place where the include directive is. Your variable will work, unless something else is trashing it between the include calls.

e.g.

core.php:

<?php
$foo = 'bar';

file1.php:

include('core.php');
$foo = 'baz';

file2.php

echo $foo; // undefined
include('core.php');
echo $foo; // outputs bar
include('file1.php');
echo $foo; // outputs baz
Sign up to request clarification or add additional context in comments.

2 Comments

I know that's how it's supposed to be but it doesn't happen to me. I copy/paste your example and the same behaviour occurs. Where I include a variable from a second file it doesn't see it. Only on the first level include
@silver14_, try to replace require_once to require first of all. Look at comments to your question.

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.