-1
我已經實現了數據庫的鏈接方法。我的問題是,當我調用數據庫類時,它會覆蓋新的變量。我怎樣才能保存我的變量。這是我的代碼。方法鏈接覆蓋變量
當我使用此代碼:
Database::('table')
->set(['name', 'test'])
->select([
Database::('table2')
->set(['name', 'test2')])
]);
它覆蓋上Database::('table')->set
和覆蓋使用新Database::('table2')->set
變量$set
變量。
數據庫類:
namespace VendorName;
class Database
{
private static $reserved_words = [
'NOW()', 'IS NOT NULL', 'IS NULL',
];
private static $connection = null;
private static $table = '';
private static $join = '';
private static $values = '';
private static $set = '';
private static $where = '';
private static $show = null;
private static $select = null;
private static $order_by = '';
private static $params = [];
/**
* Call the database table to be used.
*
* @param string $table
*/
public static function table($table)
{
self::$table .= $table;
return new static;
}
public static function set($set)
{
self::$set .= ' SET';
$index = 0;
foreach ($set as $value) {
if ($index++ > 0) {
self::$set .= ', ';
}
if (in_array($value[1], self::$reserved_words)) {
self::$set .= " {$value[0]} = {$value[1]}";
} else {
self::$set .= " {$value[0]} = ?";
}
}
if (self::checkColumn('updated_at') && self::checkColumn('updated_by')) {
self::$set .= ', updated_at = NOW(), updated_by = ' . Authentication::getAuthenticatedUser();
}
self::$params = array_merge(self::$params, $set);
return new static;
}
/**
* Create a WHERE query based on given parameters.
*
* @param array $where
*/
public static function where($where)
{
self::$where .= ' WHERE';
$index = 0;
foreach ($where as $value) {
if ($index++ > 0) {
self::$where .= ' AND';
}
if (in_array($value[1], self::$reserved_words)) {
self::$where .= " {$value[0]} {$value[1]}";
} else {
self::$where .= " {$value[0]} {$value[1]} ?";
}
}
self::$params = array_merge(self::$params, $where);
return new static;
}
/**
* select data from the database.
*
* @param array $columns
*/
public static function select($columns = ['*'])
{
self::$select = self::$connection->prepare('SELECT ' . implode(',', $columns) . ' FROM ' . self::$table . self::$join . self::$where . self::$order_by . self::$show);
$index = 1;
foreach (self::$params as $key => $value) {
if (!in_array($value[count($value) - 1], self::$reserved_words)) {
self::$select->bindValue($index++, $value[count($value) - 1]);
}
}
//echo 'SELECT ' . implode(',', $columns) . ' FROM ' . self::$table . self::$join . self::$where . self::$show;
self::$select->execute();
return new static;
}
/**
* fetch data from the database.
*
* @return array
*/
public static function fetch()
{
$result = self::$select->fetch();
self::clean();
return $result;
}
/**
* fetch data as associative array from the database.
*
* @return array
*/
public static function fetchAll()
{
$result = self::$select->fetchAll(\PDO::FETCH_ASSOC);
self::clean();
return $result;
}
}
你應該看看[如何創建一個最小的,完整的和可驗證的示例](HTTPS:/ /stackoverflow.com/help/mcve) – Cyclonecode
由於它是一個靜態屬性,因此該類的所有實例都只有一個'$ set'。 – Barmar
這聽起來像你需要了解靜態和非靜態屬性和方法之間的區別。 – Barmar