|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #50110 Static (File Scope) Variables
Submitted: 2009-11-07 05:07 UTC Modified: 2018-07-08 19:38 UTC
Avg. Score:4.8 ± 0.4
Reproduced:1 of 2 (50.0%)
Same Version:1 (100.0%)
Same OS:1 (100.0%)
From: n8grndr1087 at optonline dot net Assigned:
Status: Verified Package: Scripting Engine problem
PHP Version: * OS: *
Private report: No CVE-ID: None
Have you experienced this issue?
Rate the importance of this bug to you:

 [2009-11-07 05:07 UTC] n8grndr1087 at optonline dot net
Global variables should be able to be declared 'static'.
Static globals, like in C, would only be accessible from the current file's scope. This would be a good way to protect internal variables used behind the scenes in a particular file. 

If there is any effective way to protect variables that I overlooked, outside of PHP classes, let me know. I understand that the possibility of this depends on how the include/file processing mechanism works.

Reproduce code:
static $myvar = 1;
function get_myvar()
  global $myvar; // Since its not a true global, this may be different
  return $myvar;
function set_myvar($v)
  global $myvar;
  $myvar = $v;

echo get_myvar().'<br/>';
$myvar = 10000;
echo get_myvar();

Expected result:

Actual result:


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2009-11-07 18:19 UTC] n8grndr1087 at optonline dot net
This feature would also be useful for static (file scope) functions as well.
 [2010-12-17 12:13 UTC]
-Package: Feature/Change Request +Package: Scripting Engine problem -Operating System: Unix +Operating System: * -PHP Version: 5.2.11 +PHP Version: *
 [2012-08-11 17:44 UTC] youdontneedme at o2 dot pl
There is no information about such usage in documentation. (well, maybe that's why it does not work)

But if such usage is not documented why syntax:

static $age = 18;

is *valid* outside class?

I agree, this should have same consequences as in C lang.
 [2018-07-08 19:38 UTC]
-Status: Open +Status: Verified -Type: Feature/Change Request +Type: Documentation Problem
 [2018-07-08 19:38 UTC]
Static variables in the global scope work just like
inside function scope: the are initialized at most once,
see <>.

However, a (static) variable which is declared in file scope,
may not necessarily be declared in the global scope, e.g.

    function foo() {
        include './a.php';

    static $bar = 42;

I agree that this should be documented.

However, changing the current behavior would constitute a BC
break, and as such would need discussion on the internals@ mailing
list, and possibly the RFC process.
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Jul 19 12:01:29 2024 UTC