-1

I have two files X.php and Y.php as shown below and I am not quite able to figure out what the include statement signifies. In both, these cases the code did not do what I expected it to do. So, I would like to know how it works.

Scenario 1: Variable defined in Y is used in X

X.php

<?php
include 'web/y.php';
echo $test;
?>

Y.php

<?php
$test =  'Hello World';
?>

My Expectation: Variable $test should be accessible in X.php after the include statement

Scenario 2: Value printed in Y is used in X

X.php

<?php
include 'web/y.php';
?>

Y.php

<?php
echo 'Hello World';
?>

My Expectation: Hello World should be printed when X.php is accessed

Naveen Dennis
  • 1,223
  • 3
  • 24
  • 39
  • 2
    What did you expect, and what did you get? You just said it didn't do what you expected. – Qirel Nov 20 '16 at 18:19
  • 1
    *"I am not quite able to figure out what the include statement signifies"* - It means to "include a file inside the present called file". The manual is clear on this http://php.net/manual/en/function.include.php *"The include statement includes and evaluates the specified file. "* --- I don't quite get the question. What is it you expect it to do and what are the present results you're getting? You may also want to read http://php.net/manual/en/language.variables.scope.php and http://php.net/manual/en/function.error-reporting.php – Funk Forty Niner Nov 20 '16 at 18:19
  • @Qirel I have added my expectation of the code – Naveen Dennis Nov 20 '16 at 18:23

1 Answers1

3

Scenario 1: Variable defined in Y is used in X

Scenario 2: Value printed in Y is used in X

Both work exactly as you want, i.e. output Hello World.

If they didn't work for you, probably, you gave wrong path to y.php.

The directory structure must be as follows:

x.php
web/y.php

If you have these files in the same directory, then you shouldn't put web/ in front of y.php.

Community
  • 1
  • 1
Denis V
  • 3,290
  • 1
  • 28
  • 40