phpclassvariablesstatic

Different values for static variable in each child


Here is my problem :

I want to have different values for a static variable in each child (I don't want to instantiate the class) :

abstract class Model {
    protected static $table;
    
    static function getTable(){
        if(!static::$table){
            // ClassName in plural to match to the table Name
            static::$table = strtolower(static::class . 's');
        }
        return static::$table;
    }
}

class Service extends Model {
}

class Categorie extends Model {
}

class Information extends Model {
    static $table = 'infos'; // Overrides ClassName + s
}

And now I want to call getTable() for each child without using new :

Service::getTable(); // Return "services"
Categorie::getTable(); // Return "services"
Information::getTable(); // Return "infos"
Categorie::getTable(); //Return "servicies"

In fact, the real interest is here to create classes for each table without thinking at which table I need to access.

Any Ideas ? If you have any Ideas on how to 'clear the static cache' that could also be a solution...


Solution

  • For anyone wondering, this behaviour works since PHP 5.5

    At the time I wrote the question I was maybe lacking of knowledge, instead of trying to assign a value to the static variable if it is empty, simply directly return the value, so it won't be permanently overriden.

    abstract class Model {
        protected static $table;
        
        static function getTable(){
            if(!static::$table){
                // ClassName in plural to match to the table Name
                return strtolower(static::class . 's');
            }
            return static::$table;
        }
    }
    
    class Information extends Model {
        static $table = 'infos'; // Overrides ClassName + s
    }
    
    class Service extends Model {
    }
    
    class Categorie extends Model {
    }
    
    print(Service::getTable() . "\n"); // services
    print(Information::getTable() . "\n"); // infos
    print(Categorie::getTable() . "\n"); // categories