查看静态属性是否存在于父类的子类中(后期静态绑定)


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

父类中的代码:

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

当$_aReadOnlyDatabaseTables在子类中定义时有效,但是当$_aReadOnlyDatabaseTables不存在时抛出错误。我需要先检查这个属性是否存在。

我认为应该是这样的:

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

但是这会抛出一个语法错误,unexpected ',', expecting T_PAAMAYIM_NEKUDOTAYIM。使用$this代替static也不工作,它总是计算false。

正确的语法是什么?

你应该试试这个:

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

正确的方法是在父类中使用相同的默认值(空数组)初始化该值。这样你就可以确定这个属性是存在的。

当你单独使用一个类时,你在一个类中访问的所有东西都应该是可用的。

您应该能够使用get_class()而不是static关键字快速完成此操作:

if (property_exists(get_class($this), '_aReadOnlyDatabaseTables')) { ... }