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

3

6

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?

Td answered 18/3, 2013 at 17:32 Comment(0)
H
9

You should try this:

if(property_exists(get_called_class(), '_aReadOnlyDatabaseTables')) {
   foreach(static::$_aReadOnlyDatabaseTables AS $TableName => $aColumns){
      // Do something
   }
}
Heirdom answered 18/3, 2013 at 17:36 Comment(2)
@Td It would likely be faster and more efficient to just declare the array in your parent class and override it in children. Then you can skip the property check. The override would be done once at compile-time, and wouldn't incur additional overhead every time the method was called.Pliam
@ColinMorelli, thanks, I will do that as well, but my goal for the time being was to detect any child classes where this property wasn't implemented yet.Td
T
3

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.

Tyro answered 18/3, 2013 at 17:35 Comment(1)
This is good advise in general, but it doesn't address the question that was asked. It's also good practice to test that an array exists and that it's actually an array before attempting to loop over it.Td
C
0

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')) { ... }
Cummins answered 18/3, 2013 at 17:35 Comment(3)
$this should not be available in static methods, where I guess the OP put the code in his questionHeirdom
I didn't mention in the OP, but this is an instantiated class and a non-static method in question, accessing a static property.Td
Well, in this case $this reference is available then.Heirdom

© 2022 - 2024 — McMap. All rights reserved.