I have a page with a variable and a function:
test.php
<?php
$myVar = "myVar";
function myFunc() {
echo "myFunc()";
}
?>
The first page that includes it, can see the variable value.
<?php
echo "page1";
require_once("include/test.php");
print_r($myVar);
function GoTo2() {
$urlSite = "page2.php";
include($urlSite);
exit();
}
GoTo2();
?>
but the second page, cannot see the variable.
<?php
echo "page2n";
require_once("include/test.php");
print_r($myVar);
?>
it generates PHP Warning: Undefined variable $myVar in .../page2.php on line 4
I cannot use require() in the second page, because it generates an error – PHP Fatal error: Cannot redeclare myFunc() (previously declared in .../include/test.php) in .../include/test.php ...
What is the proper php way that both pages can see the variable and also can use the function?
EDIT:
- this is a simplified of my real pages. I just discovered that page2 cannot see the variable when the site was upgraded to php8, and I recieved all “Undefined variable” warnings.
- page1 is a “dispatcher” page
- suppose I inherited this code from another developper, what is the best solution to solve the problem?