PHP 和 PDO 类问题
问题描述
我对 OOP 风格的 PHP 很陌生,我也在尝试实现 PDO.我在网上找到了这个处理数据库连接的不错的小类,但是我不知道如何从另一个类访问它.代码如下:
I am very new to OOP styled PHP, and I am trying to implement PDO as well. I found this nice little class online which handles the database connection, however I have no idea how to access it from another class. Here is the code:
如何访问我的 Person 类中的 $db_handle
变量?我是否必须在 Person 类中实例化变量?如果是这样,那是否意味着我将始终必须将其称为 $this->db_handle
?我希望避免这种情况.(我对类的变量作用域仍然只有非常基本的了解)
How can I gain access to the $db_handle
variable inside of my Person class? Do i have to instantiate the variable inside of the Person class? If so, does that mean I will always have to call it as $this->db_handle
? I was hoping to avoid that. (I still only have a very basic understanding of variable scope with classes)
推荐答案
有(至少)三种方法来处理这个问题.最便携且经常被推荐的方法称为依赖注入",您可以通过它的 __construct()
将数据库句柄传递到您的类中,并将其存储在类变量中.需要使用 $this->db
访问它,就像您不想做的那样.
There are (at least) three ways to handle this. The most portable, and oft recommended is called "dependency injection", whereby you pass the database handle into your class via its __construct()
and store it in a class variable. Requires accessing it with $this->db
like you didn't want to have to do.
下一个方法是在构造函数中实例化 $db_handle
而不是将其传入.这有点难以测试和调试.
Next method would be to instantiate the $db_handle
inside the constructor rather than passing it in. This is a little harder to test and debug.
最后,您可以在课堂中使用 $db_handle
作为 global
调用它.这可能是最难阅读和调试的.
Finally, you can call $db_handle
as a global
whenever you use it in your class. This is perhaps the hardest to read and debug.
这篇关于PHP 和 PDO 类问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!