1

I am trying to implement something like this:

$child1_instance1 =  new \aae\web\ChildOne();
$child1_instance2 =  new \aae\web\ChildOne();
$child2_instance1 =  new \aae\web\ChildTwo();
$child2_instance2 =  new \aae\web\ChildTwo();

// setting the static variable for the first instance of each derived class
$child1_instance1->set('this should only be displayed by instances of Child 1');
$child2_instance1->set('this should only be displayed by instances of Child 2');

// echoing the static variable through the second instance of each drived class
echo $child1_instance2->get();
echo $child2_instance2->get();

//desired output:
this should only be displayed by instances of Child 1
this should only be displayed by instances of Child 2

// actual output:
this should only be displayed by instances of Child 2
this should only be displayed by instances of Child 2

with a class structure similar to this: (I know this doesn't work.)

abstract class ParentClass {
    protected static $_magical_static_propperty;

    public function set($value) {
        static::$_magical_static_propperty = $value;
    }
    public function get() {
        return static::$_magical_static_propperty;
    }
}

class ChildOne extends ParentClass { }

class ChildTwo extends ParentClass { }

How do I create static variables for each child class that are not shared across siblings?

The reason I would like to be able to do this is to be able to keep track of an event that should only happen once for each derived class, without having the client who is deriving from my parent class have to worry about the implementation of said tracking functionality. The client should be able to check though, if said event has happend.

DudeOnRock
  • 3,685
  • 3
  • 27
  • 58

1 Answers1

2

$_magical_static_propperty is shared between ChildOne and ChildTwo, so the second input will win over the first and both will display the same thing.

Demo: http://codepad.viper-7.com/8BIsxf


The only way to solve it is to give each child the protected static variable:

class ChildOne extends ParentClass { 
    protected static $_magical_static_propperty;
}

class ChildTwo extends ParentClass { 
    protected static $_magical_static_propperty;
}

Demo: http://codepad.viper-7.com/JobsWR

Naftali
  • 144,921
  • 39
  • 244
  • 303