Use global variables in the class
In PHP, global variables can be accessed from inside a class using the global
keyword. However, this may cause code readability and maintainability issues. Consider the following code example:
<code class="language-php">$db = new DB_MySQL("localhost", "root", "", "test"); // 连接数据库 include_once("pagi.php"); $pagination = new pagi(); $records = $pagination->get_records("SELECT * FROM `table`");</code>
in pagi.php
file:
<code class="language-php">class pagi { public function get_records($q) { global $db; $x = $db->query($q); return $db->fetch($x); } }</code>
This code attempts to use a get_records
variable outside the pagi
class in a $db
method. However, it results in a fatal error because global variables cannot be accessed via the ->
operator.
Dependency Injection: A Better Way
A better way to access external objects is dependency injection. In this approach, the external object is passed as a parameter to the constructor or method of the class. For example:
<code class="language-php">$db = new DB_MySQL("localhost", "root", "", "test"); // 连接数据库 include_once("pagi.php"); $pagination = new Paginator($db); $records = $pagination->get_records("SELECT the, fields, you, want, to retrieve FROM `table`");</code>
<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>
In this case, the $db
object is passed to the Paginator
class through the constructor. This allows a class to perform queries using the $db
object without setting it as a global variable or creating a new instance within the class.
Conclusion
While using global variables may be convenient, dependency injection is a more flexible and easier to maintain method of adding external functionality to a class. By passing dependencies explicitly, you decouple a class from a specific implementation and make it easier to test and maintain.
The above is the detailed content of How Can I Properly Access External Objects Within a PHP Class?. For more information, please follow other related articles on the PHP Chinese website!