79725746

Date: 2025-08-05 07:37:22
Score: 0.5
Natty:
Report link

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
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: Stephane Zundel