我需要使用getter和setter方法从/向数据库选择/插入数据。现在我想要实现的是从数据库中选择所有内容,并在html中回显出来,看看我是否收到了任何东西。
到目前为止,代码如下:
class Products extends DbConnect {
protected $id;
protected $sku;
protected $name;
protected $price;
protected $type;
protected $attributes;
public function select() {
$query = "SELECT * FROM products";
$result = $this->connect()->query($query);
$row = $result->fetch(PDO::FETCH_ASSOC);
$this->id = $row['Id'];
$this->sku = $row['SKU'];
$this->name = $row['Name'];
$this->price = $row['Price'];
$this->type = $row['Type'];
$this->attributes = $row['Attributes'];
}
public function getId() {
return $this->id;
}
public function getSKU() {
return $this->sku;
}
public function getName() {
return $this->name;
}
public function getPrice() {
return $this->price;
}
public function getType() {
return $this->type;
}
public function getAttributes() {
return $this->attributes;
}
}
我不确定我下一步要做什么。我试着看看我是否能得到像这样的数据:
public function __construct($name) {
$this->name = $name;
}
$product = new Products();
echo $product->name;
它告诉我我没有传递任何参数。在打印出所选数据之前,是否需要对其执行其他操作?我对这种方法完全陌生,我真的不确定该怎么做。
发布于 2019-05-30 17:10:30
您的构造函数需要在类中
class Products extends DbConnect {
protected $id;
protected $sku;
protected $name;
protected $price;
protected $type;
protected $attributes;
public function __construct($name) {
$this->name = $name;
}
public function select() {
$query = "SELECT * FROM products";
$result = $this->connect()->query($query);
$row = $result->fetch(PDO::FETCH_ASSOC);
$this->id = $row['Id'];
$this->sku = $row['SKU'];
$this->name = $row['Name'];
$this->price = $row['Price'];
$this->type = $row['Type'];
$this->attributes = $row['Attributes'];
}
public function getId() {
return $this->id;
}
public function getSKU() {
return $this->sku;
}
public function getName() {
return $this->name;
}
public function getPrice() {
return $this->price;
}
public function getType() {
return $this->type;
}
public function getAttributes() {
return $this->attributes;
}
}
然后在定义新类时传递参数
$product = new Products("Product Name");
echo $product->name;
我建议将构造函数更改为接受数组,这样您就可以传递任意数量的参数,而顺序并不重要。
public function __construct(array $config = []) {
$this->name = $config["name"];
$this->id = $config["id"];
}
然后你可以像这样发送任意数量的参数
$options = [
"name" => "ProductName",
"id" => "ProductID"
];
$product = new Products($options);
echo "Name: ".$product->name;
echo "ID: ".$product->id;
https://stackoverflow.com/questions/56382408
复制