Using Global Variables within a Class
Creating pagination functionality involves accessing a database object from within a class. However, attempting to access an outside variable inside the class can lead to errors. Let's delve into possible solutions to handle this issue.
To address the fatal error "Call to a member function query() on a non-object," the database object needs to be accessible within the class. Instead of using global variables, a more appropriate approach is to inject the database object into the class or its methods.
Dependency Injection
One method is to inject the database object into the class constructor, as shown below:
include_once("pagi.php"); $db = new DB_MySQL("localhost", "root", "", "test"); // connect to the database $pagination = new Paginator($db); $records = $pagination->get_records("SELECT * 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); } }
This allows the pagination class to access the database object directly.
Method Injection
Another option is to inject the database object into the specific method that requires it:
$pagination = new Paginator(); $records = $pagination->get_records("SELECT * FROM `table`", $db); class Paginator { public function get_records($q, DB_MySQL $db) { $x = $db->query($q); return $db->fetch($x); } }
This provides more flexibility when multiple methods have varying database requirements.
Benefits of Dependency Injection
Compared to using global variables, dependency injection offers several advantages:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3