【发布时间】:2015-07-07 09:37:29
【问题描述】:
我已经开始学习 PHP 中的 OOP。我设法编写代码,其中子类将扩展包含与数据库连接的超类。现在不是扩展或使用子类,有没有一种方法可以让这个连接类全局化,以便任何类都可以使用它的对象而不必扩展它?
请注意下面,我必须使用$this->pdo 来看待类的实例。有没有办法可以在这个类中实例化一个对象,比如$pdo=new PDO();,并在我想要的任何地方使用这个对象作为$pdo?
静态类在这种情况下会有帮助吗?
class connection
{
public $servername = "localhost";
public $username = "root";
public $password = "";
public $dbname = "carrental";
public $port="3306";
public $pdo;
function addConnection()
{
try {
$this->pdo = new PDO("mysql:host=$this->servername;port=$this->port;dbname=$this->dbname", $this->username, $this->password);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$this->pdo->query("use $this->dbname");
}
}
尝试过像下面这样的 Singleton,但可以在我收到致命错误和警告时告知问题所在。
(!) 致命错误:在 C:\wamp\www\carRental\index.php 第 20 行 (!)
PDOException:在 C:\wamp\www\carRental\index.php 第 20 行调用堆栈时间记忆函数位置 1 0.0012 143752 {main}( )
..\index.php:0 2 0.0012 144296 car->__construct( ) ..\index.php:50
3 0.0013 144272 连接->addConnection( ) ..\index.php:39
4 0.0989 150800 查询 ( ) ..\index.php:20
<?php
class connection
{
public $servername = "localhost";
public $username = "root";
public $password = "";
public $dbname = "carrental";
public $port="3306";
public static $pdo;
function addConnection()
{
try {
self::$pdo = new PDO("mysql:host=$this->servername;port=$this->port;dbname=$this->dbname", $this->username, $this->password);
self::$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
self::$pdo->query("use $this->dbname");
return self::$pdo;
}
}
class car
{
public $name;
public $maker;
public $type;
public $colour;
public $passanger;
public function __construct($param1,$param2,$param3,$param4,$param5)
{
$this->name=$param1;
$this->maker=$param2;
$this->type=$param3;
$this->colour=$param4;
$this->passanger=$param5;
connection::addConnection();
}
public function addCar()
{
$sql="INSERT INTO car(car_name,car_maker,car_type,car_colour,num_passanger)VALUES('{$this->name}','{$this->maker}', '{$this->type}','{$this->colour}','{$this->passanger}')";
$stmt = $this->$pdo->prepare($sql);
$stmt->execute();
echo "Data inserted!";
}
}
$car1=new car("Honda Accord","Honda","5 wheeler","Red",8);
$car1->addCar();
?>
【问题讨论】:
-
谷歌“依赖注入”
-
了解单例模式。
-
...当您阅读单例模式时,还要注意批评,例如这里:stackoverflow.com/questions/137975/…。我对数据库连接进行了第二次依赖注入,en.wikipedia.org/wiki/Dependency_injection
-
@Barmar,感谢您的建议..我研究了 Singleton 并尝试了它(上面发布)。但是您能帮我确定那里有什么问题会发出错误吗?
-
@Barmar Singleton 模式被认为是不好的,有一个很好的理由:它使编写独立测试变得困难。我会在应用程序的早期阶段创建数据库连接对象,并将其传递给在创建过程中需要它的组件。