php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #39044 Changing a static variables in a class changes it across sub/super classes.
Submitted: 2006-10-05 07:47 UTC Modified: 2006-10-05 11:21 UTC
From: matti at nitro dot fi Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.1.6 OS: *
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: matti at nitro dot fi
New email:
PHP Version: OS:

 

 [2006-10-05 07:47 UTC] matti at nitro dot fi
Description:
------------
Bug is still open in release versions. When it will be fixed?

http://bugs.php.net/bug.php?id=28442


quote------------


[19 May 2004 9:27am UTC] kell_pt at users dot sf dot net
It isn't possible to override static variable values in classes, seeing
as the same variable is shared across the whole hierarchy of classes.
Each child class should be able to have their own value for a static
variable.

A good example is trying to have a counter of the number of instances
per class.

ClassB::$count will always be the same as ClassA::$count.

It is possible that you don't consider this a bug, but it is quite
against the OOP paradigm, and worth a note. Basically, when loading a
subclass, the default values for the variables should be loaded, and a
new variable (memory space) created, instead of keeping a reference to
the superclass' static variable.

This is somehow related to Bug #16245 (which regards static variables
declared within functions). But where the behaviour in such a situation
is a bit unspecified, in this case it's quite against OO programming.

Reproduce code:
---------------
quote------------


[19 May 2004 9:27am UTC] kell_pt at users dot sf dot net

class ClassA
{
   static $count;
   static $somevar;

   static __construct()
   {
       self::$count++; // this won't work as expected
   }
}

class ClassB extends ClassA
{
}

// another simpler example
ClassA::$somevar = 'A';
ClassB::$somevar = 'B';
// ClassA::$somevar is now 'B' instead of 'A';
ClassA::$somevar = 'A';
// ClassB::$somevar is now 'A' instead of 'B';



Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2006-10-05 11:21 UTC] tony2001@php.net
This is the way C++ and Java work.
When a static member is inherited, it's the same value across all classes. But if you redeclare it in the child class, changing it wouldn't affect parent.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Wed Dec 03 09:00:01 2025 UTC