douxin8610 2016-07-13 07:26
浏览 54
已采纳

通过父类定义被调用的类属性

I have written a parent class (using late static binding) from which my database classes are inherited. I'm trying to write a constructor to assign each table column as a public property of the child classes. So far i could write the constructor in child classes, which works just fine, but I want to put it in the parent class so that all child classes properties are defined automatically. Here is my child class:

class Sale extends DatabaseObject {

    protected static $table_name="invoices";
    protected static $db_fields = array();

    function __construct() {
        global $database;
        $query_cols = " SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_NAME LIKE '" . self::$table_name . "' AND TABLE_SCHEMA LIKE '" . DB_NAME . "' ORDER BY ORDINAL_POSITION ASC";
        $cols = $database->query($query_cols);
        while($col = $database->fetch_array($cols)) {
            if(!property_exists($this,$col['COLUMN_NAME'])) {
                $this->$col['COLUMN_NAME']=NULL;
                array_push(self::$db_fields,$col['COLUMN_NAME']);
            }
        }
    }
}

To use this constructor in the parent I need to be able to define the called class property.

function __construct() {
    $class_name = get_called_class();
    $query_cols = " SELECT COLUMN_NAME FROM information_schema WHERE TABLE_NAME LIKE '" . static::$table_name . "' AND TABLE_SCHEMA LIKE '" . DB_NAME . "'";
    $query_cols .= " ORDER BY ORDINAL_POSITION ASC";
    $cols = $database->query($query_cols);
    while($col = $database->fetch_array($cols)) {
        if(!property_exists($class_name,$col['COLUMN_NAME'])) {
            // the code to define called class public property?!
        }
    }
}

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • dow46218 2016-07-13 08:14
    关注

    Generally, if you're accessing static members of a class, you can use static::$foo rather than self::$foo, however you would need to redeclare the empty initial static variable for each child class, otherwise it will use the parent's static member.

    An alternative approach I use for a Model system, is to use the class name as part of an array structure.

    So instead of

    array_push(self::$db_fields,$col['COLUMN_NAME']);
    

    you would do

    array_push(self::$db_fields[$class_name],$col['COLUMN_NAME']);
    

    This way you basically have a single array at the parent class level, with each element an array of the child class fields, keyed by their class name.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c