note 100884 added to language.variables.scope

From: Date: Fri, 12 Nov 2010 18:37:23 +0000
Subject: note 100884 added to language.variables.scope
Groups: php.notes 
Request: Send a blank email to php-notes+get-173982@lists.php.net to get a copy of this message
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. ---- Server IP: 69.147.83.197 Probable Submitter: 174.46.204.210 ---- Manual Page -- http://www.php.net/manual/en/language.variables.scope.php Edit -- https://master.php.net/note/edit/100884 Del: integrated -- https://master.php.net/note/delete/100884/integrated Del: useless -- https://master.php.net/note/delete/100884/useless Del: bad code -- https://master.php.net/note/delete/100884/bad+code Del: spam -- https://master.php.net/note/delete/100884/spam Del: non-english -- https://master.php.net/note/delete/100884/non-english Del: in docs -- https://master.php.net/note/delete/100884/in+docs Del: other reasons-- https://master.php.net/note/delete/100884 Reject -- https://master.php.net/note/reject/100884 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#173982) next »