I’m really new to programming especially OOP and I wonder how I can write this kind of functions correctly?
Is there a best practice? Maybe it depends on the readability of the code but I have no idea which is better? Personally I would prefer the third one but i want to learn the “correct” way…
// Version #1
public function getUser( $id )
{
$sql = "SELECT * FROM users WHERE id=$id";
$user = $this->database->query($sql);
return $user;
}
// Version #2
public function getUser( $id )
{
$user = $this->database->query("SELECT * FROM users WHERE id=$id");
return $user;
}
// Version #3
public function getUser( $id )
{
return $this->database->query("SELECT * FROM users WHERE id=$id");
}
All of them are wrong because you didn’t sanitize
$id, if it’s meant to be an int, the first line of your function should be:if it’s anything else it should be:
Now, to your real question. 1 and 2 have the advantage that, if your database function returns something other than a user (some functions return false on failure), you have some way to handle it in this function. In #3, you have to handle it wherever you call
getUser. This will turn into a mess. If your query ever gets longer (requiring joins, etc) you’ll probably want something more like 1 but until then, 2 is fine. Even 3 is fine if you don’t care or don’t need to handle failed query cases here.