Search code examples
phplate-static-binding

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


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?


Solution

  • You should try this:

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