0
<?php

class Base{
  protected static $somevar = false;
  public static function changeSomeVar(){
    static::$somevar = true;
  }

  public static function checkVar(){
    var_dump(static::$somevar);
  }
}

class Child1 extends Base{
  public static function setup(){
    static::changeSomeVar();
  }
}

class Child2 extends Base{

}

Child1::setup();
Child1::checkVar(); // true
Child2::checkVar(); // still true

?>

Is there a way to have Child1's $somevar different from Child2's $somevar?

(I know you could manually write protected static $somevar = false; in each subclass, but that's somewhat counter intuitive..)

1
  • "Is there a way to have Child1's $somevar different from Child2's $somevar?" --- that is what objects were developed for. Commented Sep 5, 2011 at 2:21

1 Answer 1

2

If you want a child class to have a separate class level (static) variable, you will need to re-declare the variable. So you will need protected static $somevar = false; in the child classes.

When I think about class structures in other languages, it is very intuitive to require that.

Sign up to request clarification or add additional context in comments.

5 Comments

I have a large number of static variables in this class, which keep tracks of a lot of things, and they are different for each subclass... This will make creating a subclass a really big hassle.. Is there no other way to hide that?
@ultimatebuster: why don't you create objects? Objects have separated states
Here's how this goes: I have a base class that provides a lot of functionalities. Subclasses extends from the base class and provides a little bit of object variables, but each subclass needs to track the object it spawns, hence the big issue.
I think I see some kind of a factory.. >.>.. but that's complicating my thing even futher..
@ultimatebuster: classical factory implementation is all about objects, not pure classes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.