如何在数据库连接类上使用静态属性和方法?

时间:2015-07-07 14:32:17

标签: php

任何人都可以确定这行代码有什么问题吗?我试图使db连接成为一个静态类,这样我就可以在任何类中使用全局,而不必使用$ this-> pdo。

显示的错误是:

致命错误:在第44行的C:\ wamp \ www \ carRental \ index.php中的非对象上调用成员函数prepare()

<?php
class connection
{
    public static $servername = "localhost";
    public static $username = "root";
    public static $password = "";
    public static $dbname = "carrental";
    public static $port="3306";
    public static $pdo;

    public static function addConnection()
    {
      try {
          self::$pdo = new PDO("mysql:host=self::$servername;port=self::$port;dbname=self::$dbname", self::$username, self::$password);
          self::$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      } catch(PDOException $e) {
          echo 'ERROR: ' . $e->getMessage();
      }

      self::$pdo->query("use self::$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;

    }
    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 =connection::$pdo->prepare($sql);
        $stmt->execute();
        echo "Data inserted!";
    }
}

$car1=new car("Honda Accord","Honda","5 wheeler","Red",9);
$car1->addCar();

?>

1 个答案:

答案 0 :(得分:1)

正如@ Rizier123在评论中已经说过的那样,你没有打电话给addConnection()。因此,您可能需要在类addCar()

car方法中执行此操作
$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}')";

$pdo_obj = connection::addConnection(); //get the pdo object
$stmt = $pdo_obj->prepare($sql);
$stmt->execute();
echo "Data inserted!";