Accessing External Variables Inside PHP Class Methods
Attempting to directly access a global variable ($db
) from within a class method (e.g., get_records
in the pagi
class) results in an error. This is due to variable scoping; global variables aren't automatically available inside class methods. The solution involves explicitly passing the variable into the class.
Solution: Dependency Injection
The best approach is dependency injection. This involves passing the necessary object (in this case, the database object) as an argument to the class constructor or directly to the method. This keeps the class independent of global variables, improving code maintainability and testability.
Method 1: Injecting via Constructor
<code class="language-php">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); } } $pagination = new Paginator($db); // Pass the DB object $records = $pagination->get_records("SELECT * FROM `table`");</code>
Method 2: Injecting Directly into Method
Alternatively, you can pass the database object directly to the method:
<code class="language-php">class Paginator { public function get_records($q, DB_MySQL $db) { $x = $db->query($q); return $db->fetch($x); } } $pagination = new Paginator(); $records = $pagination->get_records("SELECT * FROM `table`", $db); // Pass DB object to method</code>
Recommendation: Constructor Injection
While both methods work, constructor injection (Method 1) is generally preferred. It promotes loose coupling, making the code more modular, testable, and easier to maintain. Direct method injection (Method 2) can make the code less readable and harder to refactor. Avoid relying on global variables whenever possible.
The above is the detailed content of How Can I Access Global Variables Inside Class Methods in PHP?. For more information, please follow other related articles on the PHP Chinese website!