mooomo
1
If I have a page index.php with code
$page = 'index';
include("sayit.php");
and page sayit.php with code
echo $page;
The output is “index”
However, if I have 3 pages, index.php, sayit.php and functions.php with code:
index.php:
$page = 'index';
include("sayit.php");
sayit.php:
include("functions.php");
sayit();
and functions.php:
function sayit()
{
echo $page;
}
The output is nothing. Why does this happen?
mooomo
2
I changed the functions page to:
function sayit()
{
global $page;
echo $page;
}
and it works fine. I didn’t realize functions don’t have access to variables declared outside of them. (:
hash
3
better to do this rather than use globals
function sayit($stuff)
{
echo $stuff;
}
sayit($page);
in most of the cases, its not better to print inside the function.
can be improved as
function sayit($stuff)
{
return $stuff; //return value instead of printing which provides flexibility
}
echo sayit($page);