How can I set the value of a static property per inherited class in PHP

30 Views Asked by At

I found out that due to inheritance static properties are shared in sibling classes even when called in static context instead of self

abstract class Repository {
 protected static ?string $tableName = NULL;

 protected static getTableName(): string {
  if(static::$tableName){
   return static::$tableName;
  }
  $tableName = "";
  // business logic
  static::$tableName = $tableName;
 }
}
final class UserRepository extends Repository {
}

final class CompanyRepository extends Repository {
}

So if UserRepository::getTableName is called, even CompanyRepository::tableName is set to "user" eg, so that the if(static::$tableName){ will be TRUE in CompanyRepository context and CompanyRepository::getTableName will return "user" as well.

1

There are 1 best solutions below

0
Chris Athanasiadis On

In order to overcome this behaviour there are two solutions:

  • Redeclare the static property in each inherited class
  • Create a hash table with inherited class names as keys

Solution #1

final class UserRepository extends Repository {
 protected static ?string $tableName = NULL;
}

Where the code in abstract Repository works as is

Solution #2

Leave the inherited classes as is while change the abstract class as:

abstract class Repository {
 protected static array $tableName = [];

 protected static getTableName(): string {
  // Using `isset` for older versions
  if(isset(static::$tableName[static::class])){
   return static::$tableName[static::class];
  }
  $tableName = "";
  // business logic
  static::$tableName[static::class] = $tableName;
 }
}