note 100884 deleted from language.variables.scope by crell
| From: | crell@php.net | Date: | Thu, 31 Mar 2022 19:46:05 +0000 |
| Subject: | note 100884 deleted from language.variables.scope by crell | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-217940@lists.php.net to get a copy of this message | ||
Note Submitter: php at keith tyler dot com
----
Sometimes a variable available in global scope is not accessible via the 'global' keyword
or the $GLOBALS superglobal array. I have not been able to replicate it in original code, but it
occurs when a script is run under PHPUnit.
PHPUnit provides a variable "$filename" that reflects the name of the file loaded on its
command line. This is available in global scope, but not in object scope. For example, the following
phpUnit script (call it GlobalScope.php):
<?php
print "Global scope FILENAME [$filename]\n";
class MyTestClass extends PHPUnit_Framework_TestCase {
function testMyTest() {
global $filename;
print "Method scope global FILENAME [$filename]\n";
print "Method scope GLOBALS[FILENAME]
[".$GLOBALS["filename"]."]\n";
}
}
?>
If you run this script via "phpunit GlobalScope.php", you will get:
Global scope FILENAME [/home/ktyler/GlobalScope.php]
PHPUnit 3.4.5 by Sebastian Bergmann.
Method scope global FILENAME []
Method scope GLOBALS[FILENAME] []
.
You have to -- strange as it seems -- do the following:
<?php
$GLOBALS["filename"]=$filename;
print "Global scope FILENAME [$filename]\n";
class MyTestClass extends PHPUnit_Framework_TestCase {
function testMyTest() {
global $filename;
print "Method scope global FILENAME [$filename]\n";
print "Method scope GLOBALS[FILENAME]
[".$GLOBALS["filename"]."]\n";
}
}
?>
By doing this, both "global" and $GLOBALS work!
I don't know what it is that PHPUnit does (I know it uses Reflection) that causes a globally
available variable to be implicitly unavailable via "global" or $GLOBALS. But there it is.