简体   繁体   English

如何从php中另一个类的一个类访问连接句柄

[英]How to access a connection handle from one class in another class in php

I´m building a MVC application. 我正在构建一个MVC应用程序。 My PDO connection is in /Controller/includes/Conexao and queries are in /model/DAO 我的PDO连接位于/ Controller / includes / Conexao中,而查询位于/ model / DAO中

As I need a prepared statement I need to use the connection handle like that: 由于需要准备好的语句,因此需要使用如下连接句柄:

$stmt = $db->prepare($query);

Problem is that $db is a variable in my class Conexão and I am not able to use it in DAO class. 问题在于$ db是我的类Conexão中的变量,而我不能在DAO类中使用它。 So how could I proceed? 那我该如何进行呢?

Using old fashioned php code I could only call mysql_query but it is about to be discontinued so that´s not an option. 使用老式的php代码,我只能调用mysql_query,但是它即将停产,所以这不是一个选择。

I would avoid using globals unless there is a VERY good reason for doing so. 除非有充分的理由,否则我将避免使用全局变量。 Look into dependency injection and singletons. 研究依赖注入和单例。 There is a very nice light-weight container called Pimple that can be used for this purpose: 有一个非常好的轻量级容器,称为Pimple,可以用于此目的:

http://pimple.sensiolabs.org/ http://pimple.sensiolabs.org/

Another uglier solution would be using mysqli_query (only the old mysql is deprecated). 另一个较丑陋的解决方案是使用mysqli_query(仅弃用旧的mysql)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM