我收到错误:
$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
代替?或者我应该将它们创建为私有属性,即使它们永远不会仅仅引用更改。
答案 0 :(得分:1)
您正在从静态方法调用filterArray,这意味着您没有$ this实例。
由于filterArray的实现似乎不需要$ this,你可以将它设为静态方法并通过self::filterArray($filter, $array)