Home >Database >Mysql Tutorial >How to Avoid 'Call to a member function query() on a non-object' Errors Using Dependency Injection?
When building pagination functionality, you might encounter the error "Call to a member function query() on a non-object." This often stems from accessing variables declared outside a class from within the class itself. Let's explore better solutions.
Dependency injection provides a clean solution. Instead of relying on global variables, we pass the necessary objects (like the database connection) directly to the class. This is done through the constructor:
<code class="language-php">$db = new DB_MySQL("localhost", "root", "", "test"); // Database connection include_once("pagi.php"); $pagination = new Paginator($db); $records = $pagination->get_records("SELECT the, fields, you, want, to retrieve FROM `table`"); class Paginator { protected $db; public function __construct(DB_MySQL $db) { $this->db = $db; } public function get_records($q) { $x = $this->db->query($q); return $this->db->fetch($x); } }</code>
Alternatively, you can inject the database object directly into the method needing it:
<code class="language-php">$db = new DB_MySQL("localhost", "root", "", "test"); // Database connection include_once("pagi.php"); $pagination = new Paginator(); $records = $pagination->get_records("SELECT the, fields, you, want, to retrieve FROM `table`", $db); class Paginator { public function get_records($q, DB_MySQL $db) { $x = $db->query($q); return $db->fetch($x); } }</code>
Dependency injection offers significant advantages over using global variables:
In summary, dependency injection is a best practice for managing dependencies and shared resources, promoting cleaner, more robust, and testable code. Avoid the pitfalls of global variables by adopting this approach.
The above is the detailed content of How to Avoid 'Call to a member function query() on a non-object' Errors Using Dependency Injection?. For more information, please follow other related articles on the PHP Chinese website!