php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #51720 static properties in subclasses should take on own value w/o redeclaration
Submitted: 2010-05-02 00:01 UTC Modified: 2010-07-06 19:07 UTC
From: dtomasiewicz at gmail dot com Assigned:
Status: Not a bug Package: Class/Object related
PHP Version: 5.3.2 OS: all
Private report: No CVE-ID: None
 [2010-05-02 00:01 UTC] dtomasiewicz at gmail dot com
Description:
------------
Something I've found quite annoying about the Late Static Binding implementation 
is the need to re-declare static variables in subclasses to allow them to have 
their own values. (see Test Script)

In order to get the desired results, you need to re-declare the static variable 
in the subclasses, which of course goes against every fundamental principle of 
DRY if you're going to have a large number of subclasses and static properties. 
I can't find a work-around to this other than to re-declare the static 
variables, which sort of puts us in the same boat we were in before 5.3 when we 
would need to redeclare static methods in subclasses too.

I'm not sure why this is behaving this way-- if you don't want subclasses to 
have their own value, you should make it private or use the self:: keyword when 
referencing the variable in the superclass.

There is a note on the PHP Late Static Binding page that reads "static:: does 
not work like $this for static methods! $this-> follows the rules of inheritance 
while static:: doesn't. This difference is detailed later on this manual page." 
but the difference is NOT detailed later on that page, and I can't find any 
details whatsoever.

Test script:
---------------
<?php

class Foo {
  protected static $whoAmI;

  public static function init() {
    static::$whoAmI = get_called_class();
  }
  public static function who() {
    echo static::$whoAmI."\n";
  }
}

class BarOne extends Foo {}

class BarTwo extends Foo {}

BarOne::init(); // sets the whoAmI property in Foo to BarOne
BarTwo::init(); // sets the whoAmI property in Foo to BarTwo
BarOne::who(); // outputs "BarTwo"
BarTwo::who(); // also outputs "BarTwo"

Expected result:
----------------
BarOne
BarTwo


Actual result:
--------------
BarTwo
BarTwo


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2010-07-06 19:07 UTC] johannes@php.net
-Status: Open +Status: Bogus
 [2010-07-06 19:07 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

The protected static variable is inherited by the children. Make it private if it should belong to a specific class context.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Mar 28 19:01:29 2024 UTC