0

I am trying to execute initialize() method for each class that extends from a baseClass, by using late static bindings:

class BaseClass 
{   
    protected static $initialized = false;

    public static function find()
    {
        static::initialize();
        //TODO search entries and return as instances...
    }

    protected static function initialize() 
    {
        if (static::$initialized) 
            return;

        echo 'Initializing ', static::class, '<br/>';
        //do important stuff
        static::$initialized = true;
    }
}

class Child1 extends BaseClass {}
class Child2 extends BaseClass {}

$initialized property is being shared across the extending classes.

Child1::find(); //Outputs 'Initializing Child1', as expected
Child2::find(); //Doesn't execute 'initialize()' because 
                //$initialized property was set to true by Child1
                //Expected: 'Initializing Child2'

Is there a simple way to achieve it?

CarlosCarucce
  • 3,420
  • 1
  • 28
  • 51
  • change `$initialized` to an array, where you add initialized classes and check for the existance of the (Child-)class with `in_array()` – dognose Jun 02 '17 at 17:18

1 Answers1

0

You can change $initialized to an array (as suggested in comment) using class names as keys:

class BaseClass 
{   
    protected static $initialized = [];

    public static function find()
    {
        return static::initialize();
    }

    protected static function initialize() 
    {
        $class_name = static::class;
        if (!empty(static::$initialized[$class_name])) { 
            return static::$initialized[$class_name];
        }

        echo 'Initializing ', $class_name, '<br/>';
        //do important stuff
        static::$initialized[$class_name] = new static();
        // do another important stuff and return instance
        return static::$initialized[$class_name];
    }
}

class Child1 extends BaseClass {}
class Child2 extends BaseClass {}
arbogastes
  • 1,308
  • 9
  • 10