【发布时间】:2011-06-04 20:37:39
【问题描述】:
我刚刚开始使用 OOP PHP,遇到了一个问题。我已经设置了一个通用的 mysql 类,它允许我连接到数据库并具有一些从表中获取记录的功能:
class mysql{
//some lines to connect, followed by:
public function get_record($sql)
{
$result = mysql_result(mysql_query($sql));
return $result;
//obiously it's a bit more advanced, but you get the picture.
}
}
接下来,我有一个类来获取用户详细信息:
class user{
__construct($id)
{
$this->id = $id
}
public function get_username($id)
{
$username = get_record("SELECT name FROM users WHERE id = '".$this->id."'");
return $username;
}
}
我试过这个,但得到函数 get_record 未知的错误。我通过添加 $mysql = new mysql(); 解决了这个问题到用户类。
但是,必须为使用我的数据库方法(几乎是所有方法)的每个类实例化 mysql 对象感觉非常低效。
有没有办法让所有其他类都可以访问 mysql 类及其方法,而不必在每个方法中调用 mysql 类?
【问题讨论】:
-
请不要创建 MySQL 类。周围有太多这样的东西,即使 PHP 已经内置了这样的东西。它被称为 PDO(PHP 数据库对象)。 PDO 可以转移给其他开发人员,而不得不一次又一次地找出其他人的 MySQL 类感觉毫无意义。