我的代码:
class db_mysqls
{
private $host;
private $user;
private $password;
private $db_name;
private $port;
/** Constructor sets the object of DB_MySQL*/
public function __construct($host, $port, $user, $password, $db_name)
{
$this->host = $host;
$this->port = $port;
$this->user = $user;
$this->password = $password;
$this->db_name = $db_name;
}
/**getFromDB($statement) gets information from DB*/
public function getFromDB($query)
{
try
{
$con = new PDO("mysql:host=$this->host;port=$this->port;dbname=$this->db_name", $this->user, $this->password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
try
{
$resp = $con->query($query);
return $resp;
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
}
我想在同一个类中创建一个单独的方法来class db_mysqls
处理连接。
像这样的东西:
private $con;
private function connect()
{
global $con;
try
{
$con = new PDO("mysql:host=$this->host;port=$this->port;dbname=$this->db_name", $this- >user, $this->password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
}
/**getFromDB($statement) gets information from DB*/
public function getFromDB($query)
{
global $con;
connect(); //the call to the new function that handles connection.
try
{
$resp = $con->query($query);
return $resp;
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
}
问题是我一超出connect()
范围就会断开连接,我做错了什么?