每个子类执行一次方法

时间:2017-06-02 17:14:04

标签: php oop late-binding

我正在尝试使用late static bindings为从baseClass扩展的每个类执行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

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' 属性正在扩展类中共享。

#python file
@app.route('/models')
#@login_required
def models(): 
    allmodels = Modeldb.query.all() #THIS RETURNS A LIST FORM SQLITE3
    return render_template('models.html', allmodels=allmodels)

有没有简单的方法来实现它?

1 个答案:

答案 0 :(得分:0)

您可以使用类名作为键将$ initialized更改为数组(如注释中所示):

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 {}