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:
The above is the detailed content of How to Avoid Global Variables When Accessing a Database Object within a Class?. For more information, please follow other related articles on the PHP Chinese website!