我有一个带有方法sql()的对象Obj,它创建SQL查询来更新数据库。数据库中的表具有其ID字段的唯一名称。我的目标是能够在子对象中定义表名和ID字段名。
class Obj {
public static function sql(){
$attributes = ['something', 'else', 'whatever'];
foreach($attributes as $key => $value){
$attribute_pairs[] = "{$key}='{$value}'";
}
$sql = "UPDATE " . static::$table_name . " SET ";
$sql .= join(", ", $attribute_pairs);
$sql .= " WHERE " . static::$id_name . "='" . static::$id_name . "' ";
return $sql;
}
}
class ChildObj extends Obj{
protected static $table_name="accounts";
protected static $id_name = "account_id";
}
$test = new ChildObj;
echo $test::sql();
//returns UPDATE accounts SET 0='something', 1='else', 2='whatever' WHERE account_id='account_id'
上面代码的问题是我无法弄清楚如何引用ID字段的值。特别是这一行:
$sql .= " WHERE " . static::$id_name . "='" . static::$id_name . "' ";
返回:
account_id='account_id'
我需要它来返回'account_id'的值
account_id='#'