我是OOP和PHP的新手,所以我在这里遇到了问题。有人能告诉我,我的连接类出错了吗?它没有连接到数据库,我在try语句中尝试过var_dump($ this),它要么不起作用。此外,我正在将“dbname”更改为随机名称,代码仍然“有效”..
这是我的代码:
<?php
class connection {
// Setting Database Source Name (DSN)
public function __construct() {
$dsn = 'mysql:host=localhost;dbname=employee';
// Setting options
$options = array (PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
// Making the connection to the database
try {
$this->dbh = new PDO($dsn, 'root', '', $options);
}
catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
}
$connection = new connection();
?>
答案 0 :(得分:0)
类中的每个方法都必须返回一些东西。 尝试:
class Connection {
private $connection;
// Setting Database Source Name (DSN)
public function __construct() {
$dsn = 'mysql:host=localhost;dbname=employee';
// Setting options
$options = array (PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
// Making the connection to the database
try {
$this->connection = new PDO($dsn, 'root', '', $options);
}
catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
public function DoSomething()
{
//do something with your $this->connection and return some value;
}
}
$connection = new Connection();
echo $connection->DoSomething();