1

i am trying to find out a way to pass non global variables to included document.

page1.php

function foo()
{
   $tst =1;
   include "page2.php";
}

page2.php

echo $tst;

How can i make that variable be visible ? and how would i do this php templating so i can split header body and footer for html pages. like in a wordpress it has custom wp functions but i dont see them declaring external files to use them.

big thanks in advance.

1
  • 1
    page2.php must include page1.php, not the other way around or just use session variables Commented Jul 22, 2016 at 6:23

2 Answers 2

2

I think you are not exactly understanding what is going on. Page 1 should probably be doing the echoing. So you include page 2 and the foo function is now available. You need to call it so that it actually executes. Use the global keyword to bring a global variable into the function scope. Then you can echo it.

page1:

include "page2.php";
foo();
echo $test;

page 2:

function foo()
{
    global $test;
    $test =1;

}
Sign up to request clarification or add additional context in comments.

Comments

1

Variables in a function are not seen outside of them when they are not global. But an include in a function should be seen inside the second file.

$test="Big thing";
echo "before testFoo=".$test;

// now call the function testFoo();

testFoo();

echo "after testFoo=".$test;
Result : *after testFoo=Big thing*

function testFoo(){

  // the varuiable $test is not known in the function as it's not global

  echo "in testFoo before modification =".$test;

  // Result :*Notice: Undefined variable: test in test.php 
  // in testFoo before modification =*

  // now inside the function define a variable test. 

  $test="Tooo Big thing";
  echo "in testFoo before include =".$test;

  // Result :*in testFoo before include =Tooo Big thing*

  // now including the file test2.php

  include('test2.php');

  echo "in testFoo after include =".$test;

  // we are still in the function testFoo() so we can see the result of   test2.php
 //  Result :in testFoo after include =small thing

  }

in test2.php

echo $test;
/* Result : Tooo Big thing
   as we are still in testFoo() we know $test
   now modify $test
 */
$test = "small thing";

I hope that made the things more clear.

Comments

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.