PDO 在类中的使用
我有一些类执行一些 MySQL 查询和准备好的语句。然而,我不知道如何将我的 PDO 对象合并到这些类中。例如,我想做这样的事情:
<?php
$dbh = new PDO(...);
class Foo extends PDO {
public $dbh;
public function bar() {
$this->dbh->prepare('SELECT * FROM table');
$this->dbh->execute();
}
}
?>
不幸的是,它不起作用。谁能建议一种优雅的方法来做到这一点?感谢您抽出时间。抱歉,我是新手,如果您有任何不清楚的地方,请留下评论,我会尽力回复!
I have a few classes that perform some MySQL queries and prepared statements. However, I am lost in how to incorporate my PDO object within those classes. For example, I want to do something like this:
<?php
$dbh = new PDO(...);
class Foo extends PDO {
public $dbh;
public function bar() {
$this->dbh->prepare('SELECT * FROM table');
$this->dbh->execute();
}
}
?>
Unfortunately, it doesn't work. Can anyone suggest an elegant way to do this? Thanks for your time. Sorry I'm new to this, please leave any comments if you are unclear about anything and I'll do my best to respond!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在实现单例模式的类中实例化与数据库的连接。
连接将完成一次,并且所有其他对象/脚本都可以轻松访问此类。
我在下面的示例中使用一个名为“Core”的类;
这个类从一个名为“Config”的静态类获取参数,您可以在其中存储您的配置:
在所有脚本/对象中,您只需获取 Core 的实例,然后查询数据库
如果您需要有关单例的更多信息,请查看 PHP文档 http://php.net/manual/en/language.oop5.patterns。 php
You can instantiate your connection to the database in a class that implement the singleton pattern.
The connection will be done once and this class will be easily accessible by all of your other objects / scripts.
i use a class called "Core" in the following example;
this class take parameters from a static class called "Config" where you can store your configuration:
in all your scripts / objects you just have to get the instance of Core and then query the DB
If you need more information about singleton look at the PHP doc http://php.net/manual/en/language.oop5.patterns.php
这是一个大部分完整的工作剪辑和内容。粘贴 Guillaume Boschini 上面的答案的示例。
填充的数据库表(MySQL):
在/DBLibrary/pdocore.php中:
在/objectsLibrary/SYS_UserAddress.php中:
上面的帖子确实对我有帮助。我现在发表的这篇文章会让我更快地到达我想要的地方。仅此而已。如果有任何问题,我会及时修复。
Here is a mostly complete working cut & paste example of Guillaume Boschini's answer above.
A populated DB table (MySQL):
In /DBLibrary/pdocore.php:
In /objectsLibrary/SYS_UserAddress.php:
The post above really helped me. This post I am making now would have gotten me to where I wanted to be faster. That is all. If anything isn't right, I'll be around to fix it.
$dbh
不在Foo
的范围内,请改为这样做:此外,
Foo
不需要扩展PDO< /代码>。
$dbh
isn't within the scope ofFoo
, do this instead:Also,
Foo
doesn't need to extendPDO
.我找到了一个更好的解决方案:
当您在类外部有一个 PDO 连接并且无法在类内部使用该连接时,将该 PDO 对象作为参数发送给构造函数
///这就是我的 pdo 连接
/// 我将该类的实例创建为 obj
/ //// 类内部 :::simplified
i found a better solution :
when you have a PDO connection outside of your class and cant use that connection inside the class , send that PDO object to the constructor as a parameter
///thats my pdo connection
/// im creating the instance of that class as an obj
///// inside the class :::simplified