See if a static property exists in a child class from the parent class (late static binding)?

StackOverflow https://stackoverflow.com/questions/15483169

  •  24-03-2022
  •  | 
  •  

문제

Code in parent class:

foreach(static::$_aReadOnlyDatabaseTables AS $TableName => $aColumns){
  // Do something
}

This works when $_aReadOnlyDatabaseTables is defined in the child class, but throws an error when $_aReadOnlyDatabaseTables is absent. I need to check if this property exists first.

I think it should go something like this:

if(property_exists(static,$_aReadOnlyDatabaseTables)){
   foreach(static::$_aReadOnlyDatabaseTables AS $TableName => $aColumns){
      // Do something
   }
}

But this throws a syntax error, unexpected ',', expecting T_PAAMAYIM_NEKUDOTAYIM. Using $this in place of static doesn't work either, it always evaluates false.

What is the proper syntax for this?

도움이 되었습니까?

해결책

You should try this:

if(property_exists(get_called_class(), '_aReadOnlyDatabaseTables')) {
   foreach(static::$_aReadOnlyDatabaseTables AS $TableName => $aColumns){
      // Do something
   }
}

다른 팁

The correct way would be initializing the value with a sane default value (empty array) in the parent class. That way you can be sure that the property will exist.

Everything you access in one class should be available by properly defining it when you are using the class on its own.

You should be able to do this quick and dirty using get_class() instead of the static keyword:

if (property_exists(get_class($this), '_aReadOnlyDatabaseTables')) { ... }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top