Re: Scope of include

From: Date: Thu, 18 Jan 2007 06:44:20 +0000
Subject: Re: Scope of include
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-247297@lists.php.net to get a copy of this message
On 1/17/07, Andrew Kreps <andrew.kreps@gmail.com> wrote:
On 1/17/07, jekillen <jekillen@prodigy.net> wrote: Hello php list: If I include a php script inside a php function definition and then call the function in another script. What is the scope of variables in the included script? Are they local to the function that calls include with the file name? Thanks in advance; I'm not sure where to look for this answer; JK
FYI, I just ran a quick scope test based on my guess of your situation. If you include a PHP file containing global variables inside a function, the variables will _only_ be available after you include the file, and only for the duration of the function. They will not exist after the function ends, even if you specify global $var1; in your other functions, or at the global level of your script. This was tested using PHP 5.0.4. Here is my sample code: test.php: <? print "Top Level: Var1: $var1 Var2: $var2\n<br>"; test1(); test2(); function test1 () { print "Before: Var1: $var1 Var2: $var2\n<br>"; include("testinc.php"); print "After: Var1: $var1 Var2: $var2\n<br>"; } function test2 () { print "Test2: Var1: $var1 Var2: $var2\n<br>"; } print "Bottom Level: Var1: $var1 Var2: $var2\n<br>"; testinc.php: <? $var1 = 1; $var2 = 2; ?>

« previous php.general (#247297) next »