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 concept of a factory in PHP and how can it be used to simplify class instantiation?
- How can permissions be managed to avoid "Permission denied" errors when creating new HTML files with PHP?
- What are common issues related to file path inclusion in PHP scripts, and how can they be resolved?