Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 508
Nick Avatar asked Mar 18 '13 17:03

Nick


People also ask

What is the use of late static binding in PHP?

Late static binding was a feature introduced with php 5.3. It allows us to inherit static methods from a parent class, and to reference the child class being called.

Where can static properties be accessed?

Static properties are accessed using the Scope Resolution Operator ( :: ) and cannot be accessed through the object operator ( -> ). It's possible to reference the class using a variable.

Can we inherit static class in PHP?

In PHP, if a static attribute is defined in the parent class, it cannot be overridden in a child class.

What are static methods and properties in PHP?

The static keyword is used to declare properties and methods of a class as static. Static properties and methods can be used without creating an instance of the class. The static keyword is also used to declare variables in a function which keep their value after the function has ended.


1 Answers

You should try this:

if(property_exists(get_called_class(), '_aReadOnlyDatabaseTables')) {
   foreach(static::$_aReadOnlyDatabaseTables AS $TableName => $aColumns){
      // Do something
   }
}
like image 122
Matteo Tassinari Avatar answered Oct 11 '22 03:10

Matteo Tassinari