When should PHP classes and objects be used instead of functions for tasks like database connection or session management?
PHP classes and objects should be used instead of functions for tasks like database connection or session management when you need to encapsulate related data and functionality into a single unit. Classes allow for better organization, reusability, and maintainability of code compared to functions. Objects provide a way to create multiple instances of a class, each with its own state and behavior.
class DatabaseConnection {
private $connection;
public function __construct($host, $username, $password, $database) {
$this->connection = new mysqli($host, $username, $password, $database);
if ($this->connection->connect_error) {
die("Connection failed: " . $this->connection->connect_error);
}
}
public function query($sql) {
return $this->connection->query($sql);
}
public function close() {
$this->connection->close();
}
}
// Example usage
$db = new DatabaseConnection("localhost", "username", "password", "database_name");
$result = $db->query("SELECT * FROM table_name");
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
$db->close();
Related questions
-
fsockopen Curl sending data
-
PHP FAQ systems alternative
-
security concerns animated fonts PHP