What are the best practices for passing database instances to functions in PHP to avoid errors like "Call to a member function query() on a non-object"?
When passing database instances to functions in PHP, it's important to ensure that the instance is properly initialized and passed as a parameter to avoid errors like "Call to a member function query() on a non-object". One way to solve this issue is by checking if the database instance is valid before calling any methods on it within the function.
// Incorrect way of passing database instance to a function
function fetchData($db) {
$result = $db->query("SELECT * FROM table"); // This may cause "Call to a member function query() on a non-object" error
return $result->fetchAll();
}
// Correct way of passing database instance to a function
function fetchData($db) {
if ($db instanceof PDO) {
$result = $db->query("SELECT * FROM table");
return $result->fetchAll();
} else {
return false;
}
}
// Usage
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$data = fetchData($pdo);
Keywords
Related Questions
- What are the potential pitfalls of coding a navigation system with multiple levels of sub-links in PHP?
- How can debugging techniques be effectively utilized to troubleshoot and resolve issues with PHP scripts related to dynamic navigation menus?
- What are the best practices for setting up directory paths in PHP scripts to avoid errors related to missing directories?