0

我收到错误: 不在对象上下文中使用 $this$this->filterArray

所以我将其更改为self::filterArray并出现错误:未知:非静态方法 Abstract::filterArray() 不应静态调用

我不确定我是否正确,或者我是否应该使用抽象或接口?

基本上我要做的是设置一个array(column_name => type),这样我就可以像这样使用它来构建一个具有强制数据类型的基本插入:

    $cols = SentDAO::describe();

    foreach ($cols as $col => $type) {

        if (!isset($data[$col])) continue;

        switch ($type) {
            case self::INT:      $value = intval($data[$col]);
            case self::TEXT:     $value = $this->escape($data[$col]);
            case self::DATE_NOW: $value = 'NOW()';
        }

        $return[] = " {$col} = '{$value}'";
    }

我不想最终创建数百个不同的对象,并希望将其简单地存储在数组中。

/**
 * Abstract
 *
 */
abstract class AccountsAbstract
{
    /**
     * Data Types
     */
    const INT = "INT";
    const TEXT = "TEXT";
    const DATE_NOW = "DATE_NOW";

    /**
     * Get columns with data type
     * @param  array $filter: exclude columns
     * @return array
     */
    abstract static function describe($filter);

    /**
     * Filter from array, by unsetting element(s)
     * @param string/array $filter - match array key
     * @param array to be filtered
     * @return array
     */
    protected function filterArray($filter, $array)
    {
        if($filter === null) return $array;

        if(is_array($filter)){
            foreach($filter as $f){
                unset($array[$f]);
            }
        } else {
            unset($array[$filter]);
        }

        return $array;
    }
}


class AccountsDAO extends AccountsAbstract
{
    /**
     * Columns & Data Types.
     * @see AccountsAbstract::describe()
     */
    public static function describe($filter)
    {
        $cols = array(
            'account_id' => AccountsAbstract::INT,
            'key' => AccountsAbstract::TEXT,
            'config_id' => AccountsAbstract::INT
        );

        return $this->filterArray($cols, $filter);
    }
}

/**
 * Records
 */
class AccountsRecordsDAO extends AccountsAbstract
{
    public static function describe($filter)
    {
        $cols = array(
            'record_id' => AccountsAbstract::INT,
            'created' => AccountsAbstract::DATE_NOW,
            'customer_id' => AccountsAbstract::INT
        );

        return $this->filterArray($cols, $filter);
    }
}

/**
 * Config
 */
class AccountsConfigDAO extends AccountsAbstract
{
    public static function describe($filter)
    {
        $cols = array(
            'config_id' => AccountsAbstract::INT,
            'hidden' => AccountsAbstract::INT,
            'language_id' => AccountsAbstract::INT
        );

        return $this->filterArray($cols, $filter);
    }
}

另外我认为使用完整的类名会使代码非常混乱且不那么可移植:AccountsAbstract::INT有没有办法self::INT代替使用?或者我应该将它们创建为私有属性,即使它们永远不会只更改引用。

4

1 回答 1

1

您正在从静态方法调用 filterArray,这意味着您没有 $this 实例。

由于 filterArray 的实现似乎不需要 $this,因此您也可以将其设为静态方法并通过self::filterArray($filter, $array)

于 2013-03-18T08:53:53.290 回答