php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #50042 global variable not fully global when declared in a function within a function
Submitted: 2009-10-30 15:03 UTC Modified: 2009-10-31 08:04 UTC
From: adam dot jimenez at gmail dot com Assigned:
Status: Not a bug Package: Variables related
PHP Version: 5.3.0 OS: any
Private report: No CVE-ID: None
 [2009-10-30 15:03 UTC] adam dot jimenez at gmail dot com
Description:
------------
In the example function test2 is declared in function test.
Function test2 declares the variable $test as global.
$test is available inside test2 and outside the function but crucially not in function test.

this may seem strange practice to declare a function within a function. but it can be useful in a function or class-based template system which is including other files and projects like wordpress.
see: http://wordpress.org/support/topic/288455

Reproduce code:
---------------
<?php
function test()
{
	function test2()
	{
		global $test;
		$test='nads'."\n";
	}
	
	test2();	
	print $test; //doesn't work
}

test();
print $test; //works
?>

Expected result:
----------------
nads
nads

Actual result:
--------------
nads

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2009-10-30 15:30 UTC] johannes@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

Global doesn't make a variable global but imports a variable fro mthe global scope (outside of all functions) into the current function/method.
 [2009-10-30 19:25 UTC] adam dot jimenez at gmail dot com
//Global doesn't make a variable global but imports a variable fro mthe
global scope (outside of all functions) into the current
function/method.

so how come it's added to the $GLOBALS array and can be accessed from 
outside the function?
 [2009-10-31 08:04 UTC] adam dot jimenez at gmail dot com
after thinking about is some more this does makes sense.

Altho I think it means that what I'm trying to achieve is impossible 
with php.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Mon Oct 14 08:01:27 2024 UTC