php在静态方法调用之间保留静态变量

时间:2011-09-09 20:11:26

标签: php static-methods abstraction

我有一个带有几个静态变量和函数的php抽象泛型类。

class Generic{
    public static $ID;
    private static $tableName;
    private static $oldTableName;
    protected static $DAL;

    public static function Init($tableName, $id=null)    {

        if(self::$tableName)
            self::$oldTableName=self::$tableName;

        self::$tableName=$tableName;        

        self::$DAL = new DAL(self::$tableName);
    }

    public static function RecallTableName(){
        if(self::$oldTableName){
            self::$tableName=self::$oldTableName;
            self::$oldTableName=null;
            return true;
        }
    }

    public static function GetProperty($id, $columnName, $whereStatement = "1=1"){
        if(!self::$tableName)
            return false;

        //DO DB STUFF HERE

        return; //RETURN WHAT DB CALLS DID HERE
    }
}

有几个类使用extends从此泛型类继承。

class Part extends Generic {

    static function  Init($tableName="part",$id = null) {
        $return = parent::Init($tableName,$id);
        new Part();
        return $return;
    }

    public static function destruct(){
        parent::RecallTableName();
    }

    public function __destruct() {
        Part::destruct();
    }

    public static function  GetProperty($id, $columnName, $whereStatement = "1=1") {
        self::Init();
        return parent::GetProperty($id, $columnName, $whereStatement);
    }
}

class System extends Generic {

    static function  Init($tableName="system",$id = null) {
        $return = parent::Init($tableName,$id);
        new System();
        return $return;
    }

    public static function destruct(){
        parent::RecallTableName();
    }

    public function __destruct() {
        Part::destruct();
    }

    public static function GetProperty($id, $columnName, $whereStatement = "1=1") {
        self::Init();
        return parent::GetProperty($id, $columnName, $whereStatement);
    }

    public static function GetInventory($PartManageIDToCheck)
    {
        return Part::GetInventory($PartManageIDToCheck);
    }
}

这种方式当我对孩子实施方法调用时,我可以挂钩孩子的死亡。更进一步,我可以打电话:

System::GetInventory(1)

这将:
1 - 在Init()上拨打Generic,在Generic::$tableName中存储“系统” 2 - 确定嵌套的兄弟(部分),然后在Init()上调用Generic,然后将Generic::$tableName移至Generic::$oldTableName并将“部分存储在Generic::$tableName

这一切都没有问题。然而,当我背靠背地使用两个孩子时,它会崩溃。

System::GetProperty(1, "ID");
Part::GetProperty(3, "ID");

使用两个背对背允许Generic以某种方式持久化,以便在Generic::$tableName == "system"被调用时Part::GetProperty(3, "ID");

知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

您正在寻找的是late static binding,它是在PHP 5.3中添加的。将$ tableName的定义更改为protected static $tableName。然后在每个子类中以完全相同的方式重新声明它。

相关问题