Object-oriented programming emphasizes data encapsulation within classes. However, scenarios often arise where a class needs to interact with external resources, like a database. This article addresses the challenge of accessing external variables, such as database objects, within a class, using a pagination class as an example.
Directly accessing an external database object from within a class can lead to errors like "Call to a member function query() on a non-object." This highlights the need for structured approaches.
Two robust methods exist for managing external dependencies:
<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); } }</code>
<code class="language-php">class Paginator { public function get_records($q, DB_MySQL $db) { $x = $db->query($q); return $db->fetch($x); } }</code>
Dependency injection significantly surpasses the use of global variables:
By employing these techniques, developers can effectively manage external dependencies in their object-oriented programs, resulting in cleaner, more maintainable, and testable code.
The above is the detailed content of How Can I Access External Variables (e.g., a Database Object) Within a Class in Object-Oriented Programming?. For more information, please follow other related articles on the PHP Chinese website!