Home > Backend Development > PHP Tutorial > 怎么在class里使用pdo?

怎么在class里使用pdo?

WBOY
Release: 2016-06-06 20:24:22
Original
1410 people have browsed it

请问要怎么在class中使用pdo?

'''
$pdo = new PDO();

class a{
function a(){

<code>$pdo->query();</code>
Copy after login
Copy after login

}
function b(){

<code>$pdo->exec();
}</code>
Copy after login
Copy after login

}
'''

就是这样,在a类里的a与b方法中使用呢?

回复内容:

请问要怎么在class中使用pdo?

'''
$pdo = new PDO();

class a{
function a(){

<code>$pdo->query();</code>
Copy after login
Copy after login

}
function b(){

<code>$pdo->exec();
}</code>
Copy after login
Copy after login

}
'''

就是这样,在a类里的a与b方法中使用呢?

题主, 你要把pdo对象通过构造函数注入到类a中.(为什么不在构造函数里面直接实例化,这些是设计模式的概念,如果题主感兴趣可以google下“控制反转”)

class A{

<code>
protected $pdo;

public function __construct(PDO $pdo){
    $this->pdo = $pdo;
}

public function a1(){
    $this->pdo->query();
}

public function b(){
    $this->pdo->exec();
}</code>
Copy after login

}

$pdo = new PDO();
$aInstance = new A($pdo);

另外上面两位的答案都不是编程最佳实践,不推荐使用。

class a{
$pdo = '';
function __construct(){
$this->pdo = new PDO();
}
function a(){
$this->pdo->query();
}
function b(){

$this->pdo->exec();
}
}

用了外部的变量可以用global

<code>$pdo = new PDO();
class a{
    function a(){
        global $pdo;
        $pdo->query();
    }
}</code>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template