What are the best practices for structuring PHP classes and methods to prevent errors like "Call to a member function query() on a non-object"?
The error "Call to a member function query() on a non-object" typically occurs when trying to call a method on an object that is not properly instantiated. To prevent this error, ensure that objects are properly initialized before calling their methods. This can be achieved by using constructor methods or initializing objects within the class.
class Database {
private $connection;
public function __construct() {
$this->connection = new mysqli("localhost", "username", "password", "database");
}
public function query($sql) {
return $this->connection->query($sql);
}
}
// Example usage
$database = new Database();
$result = $database->query("SELECT * FROM table_name");
Related Questions
- What is the best practice for allowing multiple file uploads in PHP?
- What are some common applications or use cases for using DateTime class in PHP for date comparisons?
- What are the advantages and disadvantages of using HTML for formatting output in PHP, especially when dealing with date-related content?