【发布时间】:2016-08-30 01:23:43
【问题描述】:
我是 php OOP 的新手。我有一个关于我的情况的问题。
db.php
class db{
protected $db_host;
protected $db_name;
protected $db_user_name;
protected $db_pass;
public function __construct() {
$this->db_host="localhost";
$this->db_name="bs";
$this->db_user_name="root";
$this->db_pass="";
}
public function conn(){
try {
$conn = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", $this->db_user_name="root", $this->db_pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
}
}
item.php
require "../../includes/db.php";
class item{
public $user_uid;
public $last_id;
public $display_item;
public $iid;
protected $item_id;
protected $item_name;
protected $item_price;
protected $item_quantity;
public function add_item($uid,$item_id,$item_n,$item_p,$item_q){
$db = new db();
$conn=$db->conn();
$this->user_uid=$uid;
$this->item_id=$item_id;
$this->item_name=$item_n;
$this->item_price=$item_p;
$this->item_quantity=$item_q;
try {
$sql = "INSERT item(uid,item_id,item_name,item_price,item_quantity)
VALUES('$this->user_uid','$this->item_id','$this->item_name','$this->item_price','$this->item_quantity')";
$conn->exec($sql);
$this->last_id=$conn->lastInsertId();
}
catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
public function display_item($uid){
$db = new db();
$conn=$db->conn();
$this->user_uid=$uid;
try{
$sql="SELECT * FROM item where uid='$this->user_uid'";
$statement=$conn->query($sql);
while($row=$statement->fetch()){
$this->iid[]=$row['iid'];
$this->display_item[]=[$row['item_id'],$row['item_name'],$row['item_price'],$row['item_quantity']];
}
}
catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
}
从 item.php 可以看出,我必须调用
$db = new db();
$conn=$db->conn();
在 add_item() 和 display_item() 中。
这意味着我必须访问数据库连接的每个方法,我都必须这样做。有没有更简单的方法可以通过修改我的代码而不在其他类中创建 $db = new db() ?
或
我错过了一些 PHP 可以做到的功能吗?
我想要的方式
require "../../includes/db.php";
$db = new db();
$conn=$db->conn();
class item{
...
...
public function add_item($uid,$item_id,$item_n,$item_p,$item_q){
try {
$sql = "INSERT item(uid,item_id,item_name,item_price,item_quantity)
VALUES('$this->user_uid','$this->item_id','$this->item_name','$this->item_price','$this->item_quantity')";
$conn->exec($sql);
}
public function display_item($uid){
....
try{
$sql="SELECT * FROM item where uid='$this->user_uid'";
$statement=$conn->query($sql);
所以我只声明1次()
$db = new db();
$conn=$db->conn();
在类 item() 中并将其用于其余方法。
【问题讨论】:
-
只需在属性中添加conn,在构造函数中从那里连接
-
@Ghost 嗨,幽灵,很高兴再次收到您的回复。可以给我看一个例子吗?我只需要一个简单的例子就可以了!
-
我建议您研究一下依赖注入容器解决方案,例如 Pimple; pimple.sensiolabs.org 或 php-di.org
-
@Perspective 嗯.. 我不认为我的问题很复杂,比如我必须安装一些程序?如果我错了,请纠正我。谢谢
-
你是对的,它不是,它确实有一个学习曲线,但作为最佳实践学习它可能是件好事。这里有更多关于我为什么提到它作为可能的解决方案的背景; php-di.org/doc/understanding-di.html