1 回答
TA贡献1802条经验 获得超6个赞
您想在任何地方使用有什么特殊原因吗STATIC?常见的方法是使用公共的动态方法和属性。我用 PHP OOP 中建议的命名约定重写了您的示例,它有效:
<?php
class Config
{
/** @var PDO $conn */
private $conn = null;
public function __construct()
{
$host_name = "localhost";
$base_user = "root";
$base_pass = "";
$base_name = "home_page";
try {
$this->conn = new PDO("mysql:host=$host_name;dbname=$base_name", $base_user, $base_pass);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully"; // <- this is unnnesesary
} catch (PDOException $e) {
die("Something went wrong, database connection closed. Reason: " . $e->getMessage());
}
}
public function findById($table, $data, $id)
{
$stmt = $this->conn->prepare('SELECT `' . $data . '` FROM `' . $table . '` WHERE `uid` = ?');
$stmt->execute(array($id));
return $stmt->fetch(PDO::FETCH_ASSOC);
}
}
// just for test
$cfg = new Config();
print_r($cfg->findById('foo', '*', 1));
或者在你的情况下
<?php echo $cfg->findById("page_details", "Moto", 1)['Moto'] ?>
- 1 回答
- 0 关注
- 87 浏览
添加回答
举报