Home >Backend Development >PHP Tutorial >How to Properly Access External Variables (like a Database Object) within a PHP Class?
Using Global Variables in a Class
You are attempting to create a pagination class that utilizes an external variable. However, you are encountering an error: "Call to a member function query() on a non-object."
The issue arises because the external variable, $db, is not directly accessible within the class. To resolve this, we will explore two main approaches:
Approach 1: Dependency Injection
Dependency injection involves passing the database object as an argument to the class's constructor. This method ensures that the class has access to the necessary dependency.
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); } }
Approach 2: Method Injection
Alternatively, you can pass the database object as an argument to the specific method that requires it. This approach is suitable when only a few methods need access to the dependency.
class Paginator { public function get_records($q, DB_MySQL $db) { $x = $db->query($q); return $db->fetch($x); } }
The choice between these approaches depends on your specific requirements. Dependency injection is preferred when multiple methods require the dependency, while method injection is suitable for limited dependency usage.
The above is the detailed content of How to Properly Access External Variables (like a Database Object) within a PHP Class?. For more information, please follow other related articles on the PHP Chinese website!