我有一个带构造函数的简单查询方法:
class mysql_a {
public $db;
public function __construct($db) {
$this->db=$db;
}
public function find_by_id() {
$result = $this->db->query('SELECT * FROM users WHERE id=2 LIMIT 1')->fetch(PDO::FETCH_ASSOC);
return $result;
}
}
$found = new mysql_a($db);
$res = $found->find_by_id();
echo $res['username'];
如何使“find_by_id”函数静态化?我的意思是这样的:
public static function find_by_id() {
$result = self::$db->query('SELECT * FROM users WHERE id=2 LIMIT 1')->fetch(PDO::FETCH_ASSOC);
return $result;
}
我该如何执行它?我的意思是如何改变这一部分:
$found = new mysql_a($db);
$res = $found->find_by_id();
echo $res['username'];
我无法弄明白它让我疯狂......任何想法? 谢谢, GUU。
答案 0 :(得分:1)
回答你的问题
public static function db() {
static $conn;
if (!isset($conn)) {
try {
$conn = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
catch(PDOException $ex){
die '<pre>'.print_r($ex->getMessage(), true).'</pre>';
}
}
return $conn;
}
public static function find_by_id() {
$result = self::$db->query('SELECT * FROM users WHERE id=2 LIMIT 1')->fetch(PDO::FETCH_ASSOC);
return $result;
}
您必须删除构造函数并在静态函数db中创建PDO对象。
你会打电话给$found = mysql_a::find_by_id();