ZombieBunnies
ZombieBunnies

Reputation: 268

Echoing a string of data from within an include

I want to echo a string of page specific text. I don't have a problem with this when the tag is on the page but, I am having issues when it is placd within an include. Example:

index.php

<?php

$StringData1 = "String of page specific text on page echoes.";
include("IncludeHeader.php");

?>
<html>

<head></head>
<body>

<p>Start Echo Test</p>
<p>Echo Test For StringData1:  <?php echo "$StringData1"; ?></p>
<p><?php include("IncludeFile.php");?></p>
<p>Stop Echo Test</p>

</body>
</html>

IncludeHeader.php

// Many Global Variables called from various CSV Files.  To be exact $StrindData2 is actually $StringData2[1] from an array.  The array is of a row of CSV fields
$StringData2 = "String of page specific text in include won't echo.";

IncludeFile.php

Echo Test For Included StringData2:  <?php echo "$StringData2"; ?>

When index.php is run the output is:

<html>

<head></head>
<body>

<p>Start Echo Test</p>
<p>Echo Test For StringData1:  String of page specific text on page echoes.</p>
<p>Echo Test For Included StringData2:  </p>
<p>Stop Echo Test</p>

</body>
</html>

From this example, how can I get $StringData2 to echo from within the include?

Thanks for any help.

Upvotes: 1

Views: 103

Answers (2)

kal
kal

Reputation: 48

Try this code:

IncludeFile.php

  Echo "Test for Included StringData2:  $StringData2"; 

Upvotes: 0

Robert Groves
Robert Groves

Reputation: 7738

The doc states:

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.

Also that:

If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, it will follow the variable scope of that function. An exception to this rule are magic constants which are evaluated by the parser before the include occurs.

Was your example abbreviated or is that your exact code? Your original example as shown should work fine.

Your updated example should still work.

Scratch my last edit. I think you really need to come up with an abbreviated example that reproduces the same behavior.

Upvotes: 2

Related Questions