你知道OOP的事吗?
类应包含字段和/或方法。你只是用class{}
包围了一段代码。这不是编程。
阅读关于OOP在PHP - 这里是手动:http://php.net/manual/en/language.oop5.php
读它自己的好处。
编辑:
我知道下面的例子可以让你多懒,但我会采取一拍,相信你会读到更多。
实施例类的连接可以看起来像:
class Mysql {
protected $_host;
protected $_dbname;
protected $_username;
protected $_password;
protected $_db;
public function __construct($host = null, $dbname = null, $username = null, $password = null)
{
$this->_host = $host;
$this->_dbname = $dbname;
$this->_username = $username;
$this->_password = $password;
}
public function connect()
{
try {
$this->_db = new PDO('mysql:host=' . $this->_host . ';dbname=' . $this->_dbname, $this->_username, $this->_password);
}
catch(PDOException $e){
echo $e->getMessage();
}
}
public function getDb()
{
return $this->db;
}
public function setHost($host)
{
$this->_host = $host;
return $this;
}
public function getHost()
{
return $this->_host;
}
public function setDbname($dbname)
{
$this->_dbname = $dbname;
return $this;
}
public function getDbname()
{
return $this->_dbname;
}
public function setUsername($username)
{
$this->_username = $username;
return $this;
}
public function getUsername()
{
return $this->_username;
}
public function setPassword($password)
{
$this->_password = $password;
return $this;
}
public function getPassword()
{
return $this->_password;
}
}
而且示例用法:
$mysql = new Mysql('mysql1.000webhost.com', 'a8130617_skola', 'something', 'something');
$mysql->connect();
来源
2011-03-23 20:10:23
hsz
没有错,假设它正确完成。很高兴不必一遍又一遍地重写怪异的PDO连接字符串。 – 2011-03-23 20:15:40
就是这样..那好吧。你是对的,当我有一个叫做参数的概念时,为什么我会把它包装在类中?非常感谢 – 2011-03-23 20:23:58
有些东西叫做常量,包括等等。这些都可以让它简单。下面的例子并不能为你节省很多。我唯一要做的就是让你的连接对象变成静态的,否则我不会看到像这样包装它的好处。从长远来看,您最终会将编码翻一番。 – mardala 2011-03-23 23:22:37