I have an object Obj with a method sql() that creates SQL queries to update a database. The tables in the database have unique names for their ID fields. My objective is to be able to define the table name and ID field name in the child object.
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'
The problem with code above is that I have not been able to figure out how to reference the value of the ID field. This line in particular:
$sql .= " WHERE " . static::$id_name . "='" . static::$id_name . "' ";
returns this:
account_id='account_id'
Where I need it to return the value of 'account_id'
account_id='#'