【发布时间】:2013-11-17 10:48:50
【问题描述】:
所以我有一个看起来像这样的 DB 类
class db{
private $hostname = 'localhost';
private $username = 'root';
private $password = 'root';
private $con;
public function db(){
try {
$dbh = new PDO("mysql:host=$this->hostname;dbname=myDB", $this->username, $this->password);
}catch(PDOException $e){
echo $e->getMessage();
exit();
}
$this->con = $dbh;
echo 'Connected to database<br />';
}
还有我的 index.php
include('db.class.php');
include('todo.class.php');
include('dressTemplate.inc.php');
$db = new db;
$todo = new todo($db);
我的 todo.class.php 是这样开始的
class todo{
function todo(db $db){
$this->db = $db;
}
public function render($post) {
$db &= $this->db;
但后来我收到了这个通知
Notice: Undefined variable: db in todo.class.php on line 11
Notice: Object of class db could not be converted to int in todo.class.php on line 11
如何在 todo.class.php 中正确定义 db?
【问题讨论】:
-
你为什么不使用
__construct() -
我只是习惯使用类名作为构造函数,但似乎 __construct 是最佳实践。