Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Functions have no idea variables even exist

I've noticed an annoying peculiarity in PHP (running 5.2.11). If one page includes another page (and both contain their own variables and functions), both pages are aware of each others' variables. However, their functions seem to be aware of no variables at all (except those declared within the function).

My question: Why does that happen? How do I make it not happen, or what's a better way to go about this?

An example of what I'm describing follows.

Main page:

<?php
$myvar = "myvar.";
include('page2.php');

echo "Main script says: $somevar and $myvar\n";
doStuff();
doMoreStuff();
function doStuff() {
    echo "Main function says: $somevar and $myvar\n";
}
echo "The end.";
?>

page2.php:

<?php
$somevar = "Success!";

echo "Included script says: $somevar and $myvar\n";

function doMoreStuff() {
    echo "Included function says: $somevar and $myvar\n";
}
?>

The output:

Included script says: Success! and myvar.
Main script says: Success! and myvar.
Main function says: and
Included function says: and
The end.

Both pages output the variables just fine. Their functions do not.
WRYYYYYY

like image 382
doppelgreener Avatar asked Nov 21 '25 04:11

doppelgreener


1 Answers

You need to use global before using outside-defined variables in a function scope:


function doStuff() {
    global $somevar, $myvar;
    echo "Main function says: $somevar and $myvar\n";
}

More detailed explanation provided at: http://us.php.net/manual/en/language.variables.scope.php

As comments & other answers pointed out accurately, globals can be evil. Check out this article explaining just why: http://my.opera.com/zomg/blog/2007/08/30/globals-are-evil

like image 158
Joel A. Villarreal Bertoldi Avatar answered Nov 23 '25 18:11

Joel A. Villarreal Bertoldi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!